본문 바로가기
Language/Algorithm

Balanced Parentheses Checker

by Zayne 2024. 1. 4.

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;
	}
}

 

  1. 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.
  2. The solution method takes a string s as input, converts it to a character array, and iterates through each character.
  3. If the character is an opening parenthesis '(', it is pushed onto the stack.
  4. 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.
  5. If the stack is not empty, a corresponding opening parenthesis is popped from the stack.
  6. 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