Dada una secuencia de paréntesis como una string str , la tarea es encontrar si la string dada se puede equilibrar moviendo como máximo un paréntesis de su lugar original en la secuencia a cualquier otra posición.
Ejemplos:
Entrada: str = “)(()”
Salida: Sí
Como mover s[0] al final lo hará válido.
“(())”
Entrada: str = “()))(()”
Salida: No
Enfoque: el problema se puede resolver usando una pila como se explica en esta publicación. En este artículo, se analizará un enfoque que no utiliza espacio adicional.
Si la frecuencia de ‘(‘ es menor que la frecuencia de ‘)’. Si la diferencia anterior es mayor que 1, entonces la secuencia no se puede equilibrar; de lo contrario, se puede equilibrar si la diferencia general es cero.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns true if // the string can be balanced bool canBeBalanced(string s, int n) { // Count to check the difference between // the frequencies of '(' and ')' and // count_1 is to find the minimum value // of freq('(') - freq(')') int count = 0, count_1 = 0; // Traverse the given string for (int i = 0; i < n; i++) { // Increase the count if (s[i] == '(') count++; // Decrease the count else count--; // Find the minimum value // of freq('(') - freq(')') count_1 = min(count_1, count); } // If the minimum difference is greater // than or equal to -1 and the overall // difference is zero if (count_1 >= -1 && count == 0) return true; return false; } // Driver code int main() { string s = "())()("; int n = s.length(); if (canBeBalanced(s, n)) cout << "Yes"; else cout << "No"; return 0; }
Java
// Java program to toggle K-th bit of a number N class GFG { // Function that returns true if // the string can be balanced static boolean canBeBalanced(String s, int n) { // Count to check the difference between // the frequencies of '(' and ')' and // count_1 is to find the minimum value // of freq('(') - freq(')') int count = 0, count_1 = 0; // Traverse the given string for (int i = 0; i < n; i++) { // Increase the count if (s.charAt(i) == '(') count++; // Decrease the count else count--; // Find the minimum value // of freq('(') - freq(')') count_1 = Math.min(count_1, count); } // If the minimum difference is greater // than or equal to -1 and the overall // difference is zero if (count_1 >= -1 && count == 0) 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 PrinciRaj1992
Python3
# Python3 implementation of the approach # Function that returns true if # the can be balanced def canBeBalanced(s, n): # Count to check the difference between # the frequencies of '(' and ')' and # count_1 is to find the minimum value # of freq('(') - freq(')') count = 0 count_1 = 0 # Traverse the given string for i in range(n): # Increase the count if (s[i] == '('): count += 1 # Decrease the count else: count -= 1 # Find the minimum value # of freq('(') - freq(')') count_1 = min(count_1, count) # If the minimum difference is greater # than or equal to -1 and the overall # difference is zero if (count_1 >= -1 and count == 0): return True return False # Driver code s = "())()(" n = len(s) if (canBeBalanced(s, n)): print("Yes") else: print("No") # This code is contributed by Mohit Kumar
C#
// C# program to toggle K-th bit of a number N using System; class GFG { // Function that returns true if // the string can be balanced static Boolean canBeBalanced(String s, int n) { // Count to check the difference between // the frequencies of '(' and ')' and // count_1 is to find the minimum value // of freq('(') - freq(')') int count = 0, count_1 = 0; // Traverse the given string for (int i = 0; i < n; i++) { // Increase the count if (s[i] == '(') count++; // Decrease the count else count--; // Find the minimum value // of freq('(') - freq(')') count_1 = Math.Min(count_1, count); } // If the minimum difference is greater // than or equal to -1 and the overall // difference is zero if (count_1 >= -1 && count == 0) return true; return false; } // Driver code public static void Main(String []args) { String s = "())()("; int n = s.Length; if (canBeBalanced(s, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This code is contributed by Rajput-Ji
Javascript
<script> // Javascript program to find // next greater number than N // Function that returns true if // the string can be balanced function canBeBalanced( s, n) { // Count to check the difference between // the frequencies of '(' and ')' and // count_1 is to find the minimum value // of freq('(') - freq(')') var count = 0, count_1 = 0; // Traverse the given string for (var i=0; i < n; i++) { // Increase the count if (s[i] == '(') count++; // Decrease the count else count--; // Find the minimum value // of freq('(') - freq(')') count_1 = Math.min(count_1, count); } // If the minimum difference is greater // than or equal to -1 and the overall // difference is zero if (count_1 >= -1 && count == 0) return true; return false; } var s = "())()("; var n = s.length; if (canBeBalanced(s, n)) document.write("Yes"); else document.write("No"); // This code is contributed by SoumikMondal </script>
Yes
Complejidad de tiempo: O(n), donde n es la longitud de la string s.
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA