📜  打印去掉最外面的括号后得到的字符串

📅  最后修改于: 2021-09-03 04:13:50             🧑  作者: 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


Javascript


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

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

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