📌  相关文章
📜  最大化删除所有出现的子串“ab”和“ba”的成本

📅  最后修改于: 2021-09-06 06:36:27             🧑  作者: Mango

给定一个字符串S和整数PQ,其选自S分别代表去除子的“AB”“BA”的成本,任务是找到消除串“AB”的所有出现的最大成本,“BA” .

例子:

方法:该问题可以使用贪心技术解决。请按照以下步骤解决问题:

  • 遍历字符串并删除一种类型的子字符串。这可以使用贪婪方法来完成,如下所示:
    • 如果P >= Q ,删除所有出现的“ab”子串,然后删除所有出现的“ba”子串。
    • 否则,删除所有出现的“ba”子字符串,然后删除所有出现的“ab”子字符串。
  • 可以使用堆栈数据结构
  • 根据P和Q的值作为字符数组maxstr大小2的[]minstr []和初始化最大成本和分别MAXPMINP最小成本初始化我们较高的成本较低的成本字符串作为“AB”或“BA”。
  • 初始化变量,比如cost ,以存储最大成本
  • 遍历字符串并执行以下步骤:
    • 如果栈不空,并且堆叠的顶部和当前字符形式maxstr [],然后弹出栈顶部,并添加到MAXP成本。
    • 否则,将当前字符添加到堆栈中。
  • 遍历剩余的字符串。
    • 如果栈不为空且栈顶且当前字符构成 minstr[],则弹出栈顶并将minp添加到成本中。
    • 否则,将当前字符添加到堆栈中。
  • 打印成本为最大成本。

下面是上述方法的实现:

Java
// Java program for the above approach:
 
import java.util.*;
 
class GFG {
 
    // Function to find the maximum cost of
    // removing substrings "ab" and "ba" from S
    public static int MaxCollection(
        String S, int P, int Q)
    {
        // MaxStr is the substring char
        // array with larger cost
        char maxstr[]
            = (P >= Q ? "ab" : "ba").toCharArray();
 
        // MinStr is the substring char
        // array with smaller cost;
        char minstr[]
            = (P >= Q ? "ba" : "ab").toCharArray();
 
        // Denotes larger point
        int maxp = Math.max(P, Q);
 
        // Denotes smaller point
        int minp = Math.min(P, Q);
 
        // Stores cost scored
        int cost = 0;
 
        // Removing all occurrences of
        // maxstr from the S
 
        // Stack to keep track of characters
        Stack stack1 = new Stack<>();
        char[] s = S.toCharArray();
 
        // Traverse the string
        for (char ch : s) {
 
            // If the substring is maxstr
 
            if (!stack1.isEmpty()
                && (stack1.peek() == maxstr[0]
                    && ch == maxstr[1])) {
 
                // Pop from the stack
                stack1.pop();
 
                // Add maxp to cost
                cost += maxp;
            }
 
            // Push the character to the stack
            else {
 
                stack1.push(ch);
            }
        }
 
        // Remaining string after removing maxstr
        StringBuilder sb = new StringBuilder();
 
        // Find remaining string
        while (!stack1.isEmpty())
            sb.append(stack1.pop());
 
        // Reversing the string
        // retrieved from the stack
        sb = sb.reverse();
        String remstr = sb.toString();
 
        // Removing all occurences of minstr
        for (char ch : remstr.toCharArray()) {
 
            // If the substring is minstr
            if (!stack1.isEmpty()
                && (stack1.peek() == minstr[0]
                    && ch == minstr[1])) {
 
                // Pop from the stack
                stack1.pop();
 
                // Add minp to the cost
                cost += minp;
            }
 
            // Otherwise
            else {
                stack1.push(ch);
            }
        }
 
        // Return the maximum cost
        return cost;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Input String
        String S = "cbbaabbaab";
 
        // Costs
        int P = 6;
        int Q = 4;
 
        System.out.println(MaxCollection(S, P, Q));
    }
}


Python3
# Python3 program for the above approach:
 
# Function to find the maximum cost of
# removing substrings "ab" and "ba" from S
def MaxCollection(S, P, Q):
   
    # MaxStr is the substring char
    # array with larger cost
    maxstr = [i for i in ("ab" if P >= Q else "ba")]
     
    # MinStr is the substring char
    # array with smaller cost;
    minstr = [i for i in ("ba" if P >= Q else "ab")]
 
    # Denotes larger point
    maxp = max(P, Q)
 
    # Denotes smaller point
    minp = min(P, Q)
 
    # Stores cost scored
    cost = 0
 
    # Removing all occurrences of
    # maxstr from the S
 
    # Stack to keep track of characters
    stack1 = []
    s = [i for i in S]
    # Traverse the string
    for ch in s:
 
        # If the substring is maxstr
 
        if (len(stack1)>0 and (stack1[-1] == maxstr[0] and ch == maxstr[1])):
 
            # Pop from the stack
            del stack1[-1]
 
            # Add maxp to cost
            cost += maxp
 
        # Push the character to the stack
        else:
            stack1.append(ch)
 
    # Remaining string after removing maxstr
    sb = ""
 
    # Find remaining string
    while (len(stack1) > 0):
        sb += stack1[-1]
        del stack1[-1]
 
    # Reversing the string
    # retrieved from the stack
    sb = sb[::-1]
    remstr = sb
 
    # Removing all occurences of minstr
    for ch in remstr:
 
        # If the substring is minstr
        if (len(stack1) > 0 and (stack1[-1] == minstr[0] and ch == minstr[1])):
 
            #  Pop from the stack
            del stack1[-1]
 
            # Add minp to the cost
            cost += minp
 
        # Otherwise
        else:
            stack1.append(ch)
 
    # Return the maximum cost
    return cost
 
# Driver Code
if __name__ == '__main__':
 
    # Input String
    S = "cbbaabbaab"
 
    # Costs
    P = 6;
    Q = 4;
 
    print(MaxCollection(S, P, Q));
 
# This code is contributed by mohit kumar 29.


输出:
22

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live