📜  检查支架顺序是否可以与支架位置的最多一次变化保持平衡

📅  最后修改于: 2022-05-13 01:57:07.479000             🧑  作者: Mango

检查支架顺序是否可以与支架位置的最多一次变化保持平衡

给定一个不平衡的括号序列作为字符串str ,任务是通过将至多一个括号从序列中的原始位置移动到任何其他位置来确定给定字符串是否可以平衡。
例子:

方法:X视为有效括号,则肯定(X)也是有效的。如果X无效并且可以通过某个括号中的位置变化来平衡,那么它必须是X = “)(”类型,其中')'已放置在'('之前。
现在, X可以用(X)代替,因为它不会影响X的平衡性质。新字符串变为X = “()()” ,这是平衡的。
因此,如果(X)是平衡的,那么我们可以说X最多可以通过某个括号位置的一次变化来平衡。
下面是上述方法的实现:

C++
// CPP implementation of the approach
#include 
using namespace std;
 
// Function that returns true if the sequence
// can be balanced by changing the
// position of at most one bracket
bool canBeBalanced(string s, int n)
{
    // Odd length string can
    // never be balanced
    if (n % 2 == 1)
        return false;
 
    // Add '(' in the beginning and ')'
    // in the end of the string
    string k = "(";
    k += s + ")";
 
    vector d;
    int cnt = 0;
 
    for (int i = 0; i < k.length(); i++)
    {
        // If its an opening bracket then
        // append it to the temp string
        if (k[i] == '(')
            d.push_back("(");
 
        // If its a closing bracket
        else
        {
            // There was an opening bracket
            // to match it with
            if (d.size() != 0)
                d.pop_back();
 
            // No opening bracket to
            // match it with
            else
                return false;
        }
    }
 
    // Sequence is balanced
    if (d.empty())
        return true;
    return false;
}
 
// Driver Code
int main(int argc, char const *argv[])
{
    string s = ")(()";
    int n = s.length();
 
    (canBeBalanced(s, n)) ? cout << "Yes"
                  << endl : cout << "No" << endl;
    return 0;
}
 
// This code is contributed by
// sanjeev2552


Java
// Java implementation of the approach
import java.util.Vector;
 
class GFG
{
 
    // Function that returns true if the sequence
    // can be balanced by changing the
    // position of at most one bracket
    static boolean canBeBalanced(String s, int n)
    {
 
        // Odd length string can
        // never be balanced
        if (n % 2 == 1)
            return false;
 
        // Add '(' in the beginning and ')'
        // in the end of the string
        String k = "(";
        k += s + ")";
        Vector d = new Vector<>();
 
        for (int i = 0; i < k.length(); i++)
        {
 
            // If its an opening bracket then
            // append it to the temp string
            if (k.charAt(i) == '(')
                d.add("(");
 
            // If its a closing bracket
            else
            {
 
                // There was an opening bracket
                // to match it with
                if (d.size() != 0)
                    d.remove(d.size() - 1);
 
                // No opening bracket to
                // match it with
                else
                    return false;
            }
        }
 
        // Sequence is balanced
        if (d.isEmpty())
            return true;
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = ")(()";
        int n = s.length();
 
        if (canBeBalanced(s, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by
// sanjeev2552


Python3
# Python3 implementation of the approach
 
# Function that returns true if the sequence
# can be balanced by changing the
# position of at most one bracket
def canBeBalanced(s, n):
 
    # Odd length string can
    # never be balanced
    if n % 2 == 1:
        return False
 
    # Add '(' in the beginning and ')'
    # in the end of the string
    k = "("
    k = k + s+")"
    d = []
    count = 0
    for i in range(len(k)):
 
        # If its an opening bracket then
        # append it to the temp string
        if k[i] == "(":
            d.append("(")
 
        # If its a closing bracket
        else:
 
            # There was an opening bracket
            # to match it with
            if len(d)!= 0:
                d.pop()
 
            # No opening bracket to
            # match it with
            else:
                return False
     
    # Sequence is balanced
    if len(d) == 0:
        return True
    return False
 
# Driver code
S = ")(()"
n = len(S)
if(canBeBalanced(S, n)):
    print("Yes")
else:
    print("No")


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function that returns true if the sequence
    // can be balanced by changing the
    // position of at most one bracket
    static bool canBeBalanced(string s, int n)
    {
 
        // Odd length string can
        // never be balanced
        if (n % 2 == 1)
            return false;
 
        // Add '(' in the beginning and ')'
        // in the end of the string
        string k = "(";
        k += s + ")";
        List d = new List();
 
        for (int i = 0; i < k.Length; i++)
        {
 
            // If its an opening bracket then
            // append it to the temp string
            if (k[i] == '(')
                d.Add("(");
 
            // If its a closing bracket
            else
            {
 
                // There was an opening bracket
                // to match it with
                if (d.Count != 0)
                    d.RemoveAt(d.Count - 1);
 
                // No opening bracket to
                // match it with
                else
                    return false;
            }
        }
 
        // Sequence is balanced
        if (d.Count == 0)
            return true;
        return false;
    }
 
    // Driver Code
    public static void Main()
    {
        string s = ")(()";
        int n = s.Length;
 
        if (canBeBalanced(s, n))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by
// mohit kumar 29


Javascript


输出:
Yes