Created
January 5, 2023 07:07
-
-
Save lazuee/4f55b3ad584fe5503581be3364cd730e to your computer and use it in GitHub Desktop.
Balancing Parentheses Algorithm - Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
public class Main { | |
public static boolean isBalanced(String str) { | |
Stack<Character> stack = new Stack<>(); | |
for (char c : str.toCharArray()) { | |
switch (c) { | |
case '(': | |
case '{': | |
stack.push(c); | |
break; | |
case ')': | |
case '}': | |
if (stack.isEmpty() || c != getMatchingBrace(stack.peek())) { | |
return false; | |
} | |
stack.pop(); | |
break; | |
} | |
} | |
return stack.isEmpty(); | |
} | |
private static char getMatchingBrace(char c) { | |
switch (c) { | |
case '(': | |
return ')'; | |
case '{': | |
return '}'; | |
default: | |
return '\0'; | |
} | |
} | |
public static void main(String[] args) { | |
String str1 = "{{()}}"; | |
String str2 = "{{(}}"; | |
String str3 = "{{()}"; | |
String str4 = ""; | |
System.out.println(isBalanced(str1)); | |
System.out.println(isBalanced(str2)); | |
System.out.println(isBalanced(str3)); | |
System.out.println(isBalanced(str4)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment