📌  相关文章
📜  检查表达式中的平衡括号| O(1)空间| O(N ^ 2)时间复杂度

📅  最后修改于: 2021-04-24 17:50:10             🧑  作者: Mango

给定一个包含字符‘(’‘)’‘{‘‘}’‘[‘‘]’的字符串str ,任务是确定方括号是否平衡。
如果出现以下情况,支架将保持平衡:

  1. 开括号必须用相同类型的括号封闭。
  2. 开括号必须以正确的顺序关闭。

例子:

方法:

  • 保留两个变量ij来跟踪要比较的两个括号。
  • 保持一个计数,其值在遇到左括号时增加,而在遇到右括号时减少。
  • 遇到开括号时,设置j = ii = i + 1counter ++
  • 当遇到方括号减量计数并比较ij处的括号时,
    • 如果在ij括号内是一个匹配,则在ij位置取代“#”中的字符串。递增i和递减Ĵ直到遇到非“#”值或j≥0。
    • 如果ij的括号不匹配,则返回false。
  • 如果count!= 0,则返回false。

下面是上述方法的实现:

C++
// C++ implementation of the approach 
#include  
using namespace std; 
  
// This helper function is called whenever 
// closing bracket is encountered. 
// Hence count is decremented 
// j and i points to opening and closing 
// brackets to be matched respectively 
// If brackets at i and j is a match 
// replace them with "#" character and decrement j 
// to point next opening bracket to * be matched 
// Similarly, increment i to point to next closing 
// bracket to be matched 
// If j is out of bound or brackets did not match return 0 
bool helperFunc(int& count, string& s, int& i, int& j, char tocom) 
{ 
    count--; 
    if (j > -1 && s[j] == tocom) { 
        s[i] = '#'; 
        s[j] = '#'; 
        while (j >= 0 && s[j] == '#') 
            j--; 
        i++; 
        return 1; 
    } 
    else
        return 0; 
} 
  
// Function that returns true if s is a 
// valid balanced bracket string 
bool isValid(string s) 
{ 
  
    // Empty string is considered balanced 
    if (s.length() == 0) 
        return true; 
  
    else { 
        int i = 0; 
  
        // Increments for opening bracket and 
        // decrements for closing bracket 
        int count = 0; 
        int j = -1; 
        bool result; 
        while (i < s.length()) { 
            switch (s[i]) { 
            case '}': 
                result = helperFunc(count, s, i, j, '{'); 
                if (result == 0) { 
                    return false; 
                } 
                break; 
  
            case ')': 
                result = helperFunc(count, s, i, j, '('); 
                if (result == 0) { 
                    return false; 
                } 
                break; 
  
            case ']': 
                result = helperFunc(count, s, i, j, '['); 
                if (result == 0) { 
                    return false; 
                } 
                break; 
  
            default: 
                j = i; 
                i++; 
                count++; 
            } 
        } 
  
        // count != 0 indicates unbalanced parentheses 
        // this check is required to handle cases where 
        // count of opening brackets > closing brackets 
        if (count != 0) 
            return false; 
  
        return true; 
    } 
} 
  
// Driver code 
int main() 
{ 
    string str = "[[]][]()"; 
  
    if (isValid(str)) 
        cout << "Yes"; 
    else
        cout << "No"; 
  
    return 0; 
}


Java
// Java implementation of the approach 
import java.util.*; 
  
class GFG 
{ 
  
    static String s = "[[]][]()"; 
    static int count = 0; 
    static int i = 0; 
    static int j = -1; 
  
// This helper function is called whenever 
// closing bracket is encountered. 
// Hence count is decremented 
// j and i points to opening and closing 
// brackets to be matched respectively 
// If brackets at i and j is a match 
// replace them with "#" character and decrement j 
// to point next opening bracket to * be matched 
// Similarly, increment i to point to next closing 
// bracket to be matched 
// If j is out of bound or brackets did not match return 0 
static int helperFunc(char tocom) 
{ 
    count--; 
    char temp = s.charAt(j); 
    if (j > -1 && temp == tocom) 
    { 
        s = s.replace(s.charAt(i),'#'); 
        s = s.replace(s.charAt(j),'#'); 
        temp = s.charAt(j); 
        while (j >= 0 && temp == '#') 
            j--; 
        i++; 
        return 1; 
    } 
    else
        return 0; 
} 
  
// Function that returns true if s is a 
// valid balanced bracket string 
static boolean isValid() 
{ 
  
    // Empty string is considered balanced 
    if (s.length() == 0) 
        return true; 
  
    else { 
        int result; 
        while (i < s.length()) 
        { 
            char temp = s.charAt(i); 
            if(temp=='}') 
            { 
                result = helperFunc('{'); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
            else if(temp == ')') 
            { 
                result = helperFunc('('); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
  
            else if(temp == ']') 
            { 
                result = helperFunc('['); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
                  
            else
            { 
                j = i; 
                i++; 
                count++; 
            } 
        } 
  
        // count != 0 indicates unbalanced parentheses 
        // this check is required to handle cases where 
        // count of opening brackets > closing brackets 
        if (count != 0) 
            return false; 
  
        return true; 
    } 
} 
  
// Driver code 
public static void main(String args[]) 
{ 
    if (isValid()) 
    System.out.println("No"); 
    else
    System.out.println("Yes"); 
} 
  
} 
  
// This code is contributed by Surendra_Gangwar


Python3
# Python3 implementation of the approach 
  
# These are defined as global because they 
# are passed by reference 
count = 0
i = 0
j = -1
  
# This helper function is called whenever 
# closing bracket is encountered. 
# Hence count is decremented 
# j and i points to opening and closing 
# brackets to be matched respectively 
# If brackets at i and j is a match 
# replace them with "#" character and decrement j 
# to point next opening bracket to * be matched 
# Similarly, increment i to point to next closing 
# bracket to be matched 
# If j is out of bound or brackets 
# did not match return 0 
def helperFunc(s, tocom): 
    global i, j, count 
    count -= 1
    if j > -1 and s[j] == tocom: 
        s[i] = '#'
        s[j] = '#'
        while j >= 0 and s[j] == '#': 
            j -= 1
        i += 1
        return 1
    else: 
        return 0
  
# Function that returns true if s is a 
# valid balanced bracket string 
def isValid(s): 
    global i, j, count 
  
    # Empty string is considered balanced 
    if len(s) == 0: 
        return True
    else: 
  
        # Increments for opening bracket and 
        # decrements for closing bracket 
        result = False
        while i < len(s): 
            if s[i] == '}': 
                result = helperFunc(s, '{') 
                if result == 0: 
                    return False
            elif s[i] == ')': 
                result = helperFunc(s, '(') 
                if result == 0: 
                    return False
            elif s[i] == ']': 
                result = helperFunc(s, '[') 
                if result == 0: 
                    return False
            else: 
                j = i 
                i += 1
                count += 1
  
        # count != 0 indicates unbalanced parentheses 
        # this check is required to handle cases where 
        # count of opening brackets > closing brackets 
        if count != 0: 
            return False
        return True
  
# Driver Code 
if __name__ == "__main__": 
    string = "[[]][]()"
    string = list(string) 
  
    print("Yes") if isValid(string) else print("No") 
  
# This code is contributed by 
# sanjeev2552


C#
// C# implementation of the approach
using System;
  
class GFG{
  
static string s = "[[]][]()";
static int count = 0;
static int i = 0;
static int j = -1;
  
// This helper function is called whenever
// closing bracket is encountered. Hence 
// count is decremented j and i points to
// opening and closing brackets to be matched 
// respectively. If brackets at i and j is a match
// replace them with "#" character and decrement j
// to point next opening bracket to * be matched
// Similarly, increment i to point to next closing
// bracket to be matched. If j is out of bound or
// brackets did not match return 0
static int helperFunc(char tocom)
{
    count--;
    char temp = s[j];
      
    if (j > -1 && temp == tocom) 
    {
        s = s.Replace(s[i],'#');
        s = s.Replace(s[j],'#');
          
        temp = s[j];
        while (j >= 0 && temp == '#')
            j--;
              
        i++;
        return 1;
    }
    else
        return 0;
}
  
// Function that returns true if s is a
// valid balanced bracket string
static bool isValid()
{
  
    // Empty string is considered balanced
    if (s.Length == 0)
        return true;
  
    else 
    {
        int result;
         while (i < s.Length) 
        { 
            char temp = s[i]; 
            if(temp == '}') 
            { 
                result = helperFunc('{'); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
              
            else if(temp == ')') 
            { 
                result = helperFunc('('); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
    
            else if(temp == ']') 
            { 
                result = helperFunc('['); 
                if (result == 0)  
                { 
                    return false; 
                } 
            } 
                    
            else
            { 
                j = i; 
                i++; 
                count++; 
            } 
        } 
          
        // count != 0 indicates unbalanced 
        // parentheses this check is required 
        // to handle cases where count of opening
        // brackets > closing brackets 
        if (count != 0)
            return false;
  
        return true;
    }
}
  
// Driver code
public static void Main(string []args)
{
    if (isValid())
    {
        Console.Write("No");
    }
    else
    {
        Console.Write("Yes");
    }
}
}
  
// This code is contributed by rutvik_56


输出:
Yes