📌  相关文章
📜  打印除去最外面的括号后获得的字符串

📅  最后修改于: 2021-04-23 22:30:46             🧑  作者: Mango

给定一个有效的括号字符串str ,该字符串包含小写字母,左括号和右括号,任务是通过除去最外面的括号来找到该字符串,以使该字符串仍然是有效的括号字符串。

例子:

方法:我们的想法是遍历字符串的字符和分别计数连续开括号的从字符串的两端的数闭括号。然后,迭代字符呈现内部字符串中并计数,以平衡所需要的字符串开口括号的数目。请按照以下步骤解决问题:

请按照以下步骤解决问题:

  • 初始化一个变量,例如cnt = 0 ,以存储有效括号的计数,以使str [cnt] ==’(’str [N – cnt – 1] ==’)’
  • 要通过外部括号平衡字符串的内部括号,请遍历子字符串{str [cnt],…,str [N – cnt – 1]}并计算平衡内部子字符串所需的最小开头或结尾括号,例如cntMinpar
  • 最后,更新cnt + = cntMinPair并打印子字符串{str [cnt],…,str [N – cnt]}

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
  
// Function to remove outermost
// enclosing brackets from both end
void removeBrakets(string str)
{
     
    // Stores length of the string
    int n = str.length();
  
    // Stores count of parenthesis such
    // that str[cnt] == cnt[N - cnt - 1]
    int cnt = 0;
  
    // Calculating maximum number of
    // bracket pair from the end side
    while (cnt < n && str[cnt] == '(' &&
              str[n - cnt - 1] == ')')
    {
         
        // Update cnt
        cnt++;
    }
  
    // Stores minimum outer parenthesis
    // required to balance the substring
    // { str[cnt], ..., [n - cnt -1]
    int error = 0;
          
    // Stores count of unbalanced parenthesis
    // in { str[cnt], ..., [n - cnt -1]
    int open = 0;
  
    // Traverse the substring
    // { str[cnt], ..., [n - cnt -1]
    for(int i = cnt; i < n - cnt; i++)
    {
         
        // If current charcter is '('
        if (str[i] == '(')
        {
  
            // Update cntUnbal
            open++;
        }
  
        // Decrease num, if the current
        // character is ')'
        else if (str[i] == ')')
        {
  
            // Update cntUnbal
            if(open>0){
              open--;
            }
              else{
              error++;
            }
        }
    }
  
    int rem=cnt-error;
  
    // Print resultant string
    cout << str.substr(rem, n - 2*rem) << endl;    
}
     
// Driver Code
int main()
{
     
    // Input string
    string str = "((((a)b)(c)))";
    removeBrakets(str);
  
    return 0;
}
 
// This code is contributed by susmitakundugoaldanga


Java
// Java program to implement
// the above approach
 
import java.util.*;
import java.lang.*;
class GFG {
 
    // Function to remove outermost
    // enclosing brackets from both end
    static void removeBrakets(String str)
    {
        // Stores length of the string
        int n = str.length();
 
        // Stores count of parenthesis such
        // that str[cnt] == cnt[N - cnt - 1]
        int cnt = 0;
 
        // Calculating maximum number of
        // bracket pair from the end side
        while (cnt < n && str.charAt(cnt) == '('
               && str.charAt(n - cnt - 1) == ')') {
 
            // Update cnt
            cnt++;
        }
 
        // Stores minimum outer parenthesis
        // required to balance the substring
        // { str[cnt], ..., [n - cnt -1]
        int cntMinPar = 0;
 
        // Stores count of unbalanced parenthesis
        // in { str[cnt], ..., [n - cnt -1]
        int cntUnbal = 0;
 
        // Traverse the substring
        // { str[cnt], ..., [n - cnt -1]
        for (int i = cnt; i < n - cnt;
             i++) {
 
            // If current charcter is '('
            if (str.charAt(i) == '(') {
 
                // Update cntUnbal
                cntUnbal++;
            }
 
            // Decrease num, if the current
            // character is ')'
            else if (str.charAt(i) == ')') {
 
                // Update cntUnbal
                cntUnbal--;
            }
 
            // Update cntMinPar
            cntMinPar = Math.min(
                cntMinPar, cntUnbal);
        }
 
        // Update cnt
        cnt += cntMinPar;
 
        // Print resultant string
        System.out.println(
            str.substring(cnt, n - cnt));
    }
 
    // Driver Code
    public static void main(
        String[] args)
    {
        // Input string
        String str = "((((a)b)(c)))";
        removeBrakets(str);
    }
}


Python3
# Python3 program to implement
# the above approach
 
# Function to remove outermost
# enclosing brackets from both end
def removeBrakets(str):
     
    # Stores length of the string
    n = len(str)
 
    # Stores count of parenthesis such
    # that str[cnt] == cnt[N - cnt - 1]
    cnt = 0
 
    # Calculating maximum number of
    # bracket pair from the end side
    while (cnt < n and str[cnt] == '(' and
               str[n - cnt - 1] == ')'):
 
        # Update cnt
        cnt += 1
 
    # Stores minimum outer parenthesis
    # required to balance the substring
    # { str[cnt], ..., [n - cnt -1]
    cntMinPar = 0
 
    # Stores count of unbalanced parenthesis
    # in { str[cnt], ..., [n - cnt -1]
    cntUnbal = 0
 
    # Traverse the substring
    # { str[cnt], ..., [n - cnt -1]
    for i in range(cnt, n - cnt):
         
        # If current charcter is '('
        if (str[i] == '('):
             
            # Update cntUnbal
            cntUnbal += 1
             
        # Decrease num, if the current
        # character is ')'
        elif str[i] == ')':
             
            # Update cntUnbal
            cntUnbal -= 1
 
        # Update cntMinPar
        cntMinPar = min(cntMinPar,
                        cntUnbal)
 
    # Update cnt
    cnt += cntMinPar
 
    # Print resultant string
    print(str[cnt: n - cnt])
 
# Driver Code
if __name__ == '__main__':
     
    # Input string
    str = "((((a)b)(c)))"
     
    removeBrakets(str)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
class GFG {
 
    // Function to remove outermost
    // enclosing brackets from both end
    static void removeBrakets(String str)
    {
        // Stores length of the string
        int n = str.Length;
 
        // Stores count of parenthesis such
        // that str[cnt] == cnt[N - cnt - 1]
        int cnt = 0;
 
        // Calculating maximum number of
        // bracket pair from the end side
        while (cnt < n && str[cnt] == '('
               && str[n - cnt - 1] == ')')
        {
 
            // Update cnt
            cnt++;
        }
 
        // Stores minimum outer parenthesis
        // required to balance the substring
        // { str[cnt], ..., [n - cnt -1]
        int cntMinPar = 0;
 
        // Stores count of unbalanced parenthesis
        // in { str[cnt], ..., [n - cnt -1]
        int cntUnbal = 0;
 
        // Traverse the substring
        // { str[cnt], ..., [n - cnt -1]
        for (int i = cnt; i < n - cnt;
             i++)
        {
 
            // If current charcter is '('
            if (str[i] == '(')
            {
 
                // Update cntUnbal
                cntUnbal++;
            }
 
            // Decrease num, if the current
            // character is ')'
            else if (str[i] == ')')
            {
 
                // Update cntUnbal
                cntUnbal--;
            }
 
            // Update cntMinPar
            cntMinPar = Math.Min(
                cntMinPar, cntUnbal);
        }
 
        // Update cnt
        cnt += cntMinPar;
 
        // Print resultant string
        Console.WriteLine(
            str.Substring(cnt, n - cnt - 2));
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Input string
        string str = "((((a)b)(c)))";
        removeBrakets(str);
    }
}
 
// This code is contributed by AnkThon


输出:
((a)b)(c)

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