Example
Input : (()(()))(()
Output : NO
My answer:
import java.util.*;
class BalancedParenthesesChecker {
public static void main(String[] args) {
BalancedParenthesesChecker t = new BalancedParenthesesChecker();
Scanner kb = new Scanner(System.in);
String s = kb.nextLine();
System.out.println(t.solution(s));
}
String solution(String s) {
char[] ca = s.toCharArray();
Stack<Character> st = new Stack<>();
for(char c : ca) {
if(c == '(') st.push(c);
else {
if(st.isEmpty()) return "NO";
st.pop();
}
}
String answer = "YES";
if(!st.isEmpty()) return "NO";
return answer;
}
}
- The main method initializes an instance of the BalancedParenthesesChecker class, reads a string input from the user, and then calls the solution method to check if the parentheses in the input string are balanced.
- The solution method takes a string s as input, converts it to a character array, and iterates through each character.
- If the character is an opening parenthesis '(', it is pushed onto the stack.
- If the character is a closing parenthesis ')', the program checks if the stack is empty. If it is, the parentheses are not balanced, and "NO" is returned.
- If the stack is not empty, a corresponding opening parenthesis is popped from the stack.
- After processing all characters, the program checks if the stack is empty. If it is, the parentheses are balanced, and "YES" is returned. Otherwise, "NO" is returned.
'Language > Algorithm' 카테고리의 다른 글
Anagram Counting Algorithm (1) | 2024.01.02 |
---|---|
Distinct Element Subarrays (0) | 2024.01.01 |
Anagram (0) | 2023.12.30 |
Frequency Analyzer (0) | 2023.12.29 |
Count Consecutive Sums (0) | 2023.12.27 |