📜  检查给定的字符串可以转换为平衡括号序列

📅  最后修改于: 2021-09-07 02:01:55             🧑  作者: Mango

给定的字符串的大小的S N组成的“(”,“)”,“$”,该任务是通过用替换的$每次发生任一来检查给定的字符串是否可被转换成一个平衡的支架序列)( .

例子:

方法:上述问题可以通过使用Stack来解决。这个想法是检查所有) 是否可以与($平衡,反之亦然。请按照以下步骤解决此问题:

  • “(”“)”“$”的频率分别存储在countOpencountClosedcountSymbol等变量中。
  • 将变量ans初始化为1以存储所需的结果,并将堆栈stack_1 初始化为检查所有“)”是否可以与“(”$平衡。
  • 使用变量i遍历字符串S并执行以下操作:
    • 如果当前字符S[i]“)” ,如果stack_1为空,则将ans设置为0 ,否则从stack_1弹出字符。
    •  否则将字符S[i]推送到stack_1
  • 反转字符串S ,并按照相同的步骤检查是否所有“(”都可以与“)”“$”平衡。
  • 如果countSymbol的值小于countOpencountClosed的绝对差,则将ans设置为0 。否则用符号平衡额外的括号。如果countSymbol为奇数,则平衡后,将ans设置为0
  • 经过以上步骤,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if the string
// can be balanced by replacing the
// '$' with opening or closing brackets
bool canBeBalanced(string sequence)
{
    // If string can never be balanced
    if (sequence.size() % 2)
        return false;
 
    // Declare 2 stacks to check if all
    // ) can be balanced with ( or $
    // and vice-versa
    stack stack_, stack2_;
 
    // Store the count the occurence
    // of (, ) and $
    int countOpen = 0, countClosed = 0;
    int countSymbol = 0;
 
    // Traverse the string
    for (int i = 0;
         i < sequence.size(); i++) {
 
        if (sequence[i] == ')') {
 
            // Increment closed bracket
            // count by 1
            countClosed++;
 
            // If there are no opening
            // bracket to match it
            // then return false
            if (stack_.empty()) {
                return false;
            }
 
            // Otherwise, pop the character
            // from the stack
            else {
                stack_.pop();
            }
        }
 
        else {
 
            // If current character is
            // an opening bracket or $,
            // push it to the stack
            if (sequence[i] == '$') {
 
                // Increment symbol
                // count by 1
                countSymbol++;
            }
            else {
 
                // Increment open
                // bracket count by 1
                countOpen++;
            }
            stack_.push(sequence[i]);
        }
    }
 
    // Traverse the string from end
    // and repeat the same process
    for (int i = sequence.size() - 1;
         i >= 0; i--) {
 
        if (sequence[i] == '(') {
 
            // If there are no closing
            // brackets to match it
            if (stack2_.empty()) {
                return false;
            }
 
            // Otherwise, pop character
            // from stack
            else {
                stack2_.pop();
            }
        }
        else {
            stack2_.push(sequence[i]);
        }
    }
 
    // Store the extra ( or ) which
    // are not balanced yet
    int extra = abs(countClosed - countOpen);
 
    // Check if $ is available to
    // balance the extra brackets
    if (countSymbol < extra) {
        return false;
    }
 
    else {
 
        // Count ramaining $ after
        // balancing extra ( and )
        countSymbol -= extra;
 
        // Check if each pair of $
        // is convertable in ()
        if (countSymbol % 2 == 0) {
            return true;
        }
    }
    return false;
}
 
// Driver Code
int main()
{
    string S = "()($";
 
    // Function Call
    if (canBeBalanced(S)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to check if the String
// can be balanced by replacing the
// '$' with opening or closing brackets
static boolean canBeBalanced(String sequence)
{
   
    // If String can never be balanced
    if (sequence.length() % 2 == 1)
        return false;
 
    // Declare 2 stacks to check if all
    // ) can be balanced with ( or $
    // and vice-versa
    Stack stack_ = new Stack();
    Stack stack2_ = new Stack();
 
    // Store the count the occurence
    // of (, ) and $
    int countOpen = 0, countClosed = 0;
    int countSymbol = 0;
 
    // Traverse the String
    for (int i = 0;
         i < sequence.length(); i++)
    {
 
        if (sequence.charAt(i) == ')')
        {
 
            // Increment closed bracket
            // count by 1
            countClosed++;
 
            // If there are no opening
            // bracket to match it
            // then return false
            if (stack_.isEmpty())
            {
                return false;
            }
 
            // Otherwise, pop the character
            // from the stack
            else
            {
                stack_.pop();
            }
        }
 
        else
        {
 
            // If current character is
            // an opening bracket or $,
            // push it to the stack
            if (sequence.charAt(i) == '$')
            {
 
                // Increment symbol
                // count by 1
                countSymbol++;
            }
            else
            {
 
                // Increment open
                // bracket count by 1
                countOpen++;
            }
            stack_.add(sequence.charAt(i));
        }
    }
 
    // Traverse the String from end
    // and repeat the same process
    for (int i = sequence.length() - 1;
         i >= 0; i--)
    {
 
        if (sequence.charAt(i) == '(')
        {
 
            // If there are no closing
            // brackets to match it
            if (stack2_.isEmpty())
            {
                return false;
            }
 
            // Otherwise, pop character
            // from stack
            else
            {
                stack2_.pop();
            }
        }
        else
        {
            stack2_.add(sequence.charAt(i));
        }
    }
 
    // Store the extra ( or ) which
    // are not balanced yet
    int extra = Math.abs(countClosed - countOpen);
 
    // Check if $ is available to
    // balance the extra brackets
    if (countSymbol < extra)
    {
        return false;
    }
 
    else
    {
 
        // Count ramaining $ after
        // balancing extra ( and )
        countSymbol -= extra;
 
        // Check if each pair of $
        // is convertable in ()
        if (countSymbol % 2 == 0)
        {
            return true;
        }
    }
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "()($";
 
    // Function Call
    if (canBeBalanced(S))
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to check if the
# can be balanced by replacing the
# '$' with opening or closing brackets
def canBeBalanced(sequence):
     
    # If string can never be balanced
    if (len(sequence) % 2):
        return False
 
    # Declare 2 stacks to check if all
    # ) can be balanced with ( or $
    # and vice-versa
    stack_, stack2_ = [], []
 
    # Store the count the occurence
    # of (, ) and $
    countOpen ,countClosed = 0, 0
    countSymbol = 0
 
    # Traverse the string
    for i in range(len(sequence)):
        if (sequence[i] == ')'):
 
            # Increment closed bracket
            # count by 1
            countClosed += 1
 
            # If there are no opening
            # bracket to match it
            # then return False
            if (len(stack_) == 0):
                return False
 
            # Otherwise, pop the character
            # from the stack
            else:
                del stack_[-1]
        else:
 
            # If current character is
            # an opening bracket or $,
            # push it to the stack
            if (sequence[i] == '$'):
 
                # Increment symbol
                # count by 1
                countSymbol += 1
            else:
 
                # Increment open
                # bracket count by 1
                countOpen += 1
            stack_.append(sequence[i])
 
    # Traverse the string from end
    # and repeat the same process
    for i in range(len(sequence)-1, -1, -1):
        if (sequence[i] == '('):
 
            # If there are no closing
            # brackets to match it
            if (len(stack2_) == 0):
                return False
 
            # Otherwise, pop character
            # from stack
            else:
                del stack2_[-1]
        else :
            stack2_.append(sequence[i])
 
    # Store the extra ( or ) which
    # are not balanced yet
    extra = abs(countClosed - countOpen)
 
    # Check if $ is available to
    # balance the extra brackets
    if (countSymbol < extra):
        return False
    else :
 
        # Count ramaining $ after
        # balancing extra ( and )
        countSymbol -= extra
 
        # Check if each pair of $
        # is convertable in ()
        if (countSymbol % 2 == 0) :
            return True
    return False
 
# Driver Code
if __name__ == '__main__':
    S = "()($"
 
    # Function Call
    if (canBeBalanced(S)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to check if the String
  // can be balanced by replacing the
  // '$' with opening or closing brackets
  static bool canBeBalanced(String sequence)
  {
 
    // If String can never be balanced
    if (sequence.Length % 2 == 1)
      return false;
 
    // Declare 2 stacks to check if all
    // ) can be balanced with ( or $
    // and vice-versa
    Stack stack_ = new Stack();
    Stack stack2_ = new Stack();
 
    // Store the count the occurence
    // of (, ) and $
    int countOpen = 0, countClosed = 0;
    int countSymbol = 0;
 
    // Traverse the String
    for (int i = 0;
         i < sequence.Length; i++)
    {
      if (sequence[i] == ')')
      {
 
        // Increment closed bracket
        // count by 1
        countClosed++;
 
        // If there are no opening
        // bracket to match it
        // then return false
        if (stack_.Count==0)
        {
          return false;
        }
 
        // Otherwise, pop the character
        // from the stack
        else
        {
          stack_.Pop();
        }
      }
 
      else
      {
 
        // If current character is
        // an opening bracket or $,
        // push it to the stack
        if (sequence[i] == '$')
        {
 
          // Increment symbol
          // count by 1
          countSymbol++;
        }
        else
        {
 
          // Increment open
          // bracket count by 1
          countOpen++;
        }
        stack_.Push(sequence[i]);
      }
    }
 
    // Traverse the String from end
    // and repeat the same process
    for (int i = sequence.Length - 1;
         i >= 0; i--)
    {
 
      if (sequence[i] == '(')
      {
 
        // If there are no closing
        // brackets to match it
        if (stack2_.Count == 0)
        {
          return false;
        }
 
        // Otherwise, pop character
        // from stack
        else
        {
          stack2_.Pop();
        }
      }
      else
      {
        stack2_.Push(sequence[i]);
      }
    }
 
    // Store the extra ( or ) which
    // are not balanced yet
    int extra = Math.Abs(countClosed - countOpen);
 
    // Check if $ is available to
    // balance the extra brackets
    if (countSymbol < extra)
    {
      return false;
    }
 
    else
    {
 
      // Count ramaining $ after
      // balancing extra ( and )
      countSymbol -= extra;
 
      // Check if each pair of $
      // is convertable in ()
      if (countSymbol % 2 == 0)
      {
        return true;
      }
    }
    return false;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String S = "()($";
 
    // Function Call
    if (canBeBalanced(S))
    {
      Console.Write("Yes");
    }
    else
    {
      Console.Write("No");
    }
  }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
Yes

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

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