Last active
December 25, 2016 00:16
-
-
Save lobster1234/449358077c019f0bfa810fe2c627c6d0 to your computer and use it in GitHub Desktop.
Code to match brackets - my O(N) submission to HackerRank
This file contains hidden or 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.io.*; | |
import java.util.*; | |
import java.text.*; | |
import java.math.*; | |
import java.util.regex.*; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int t = in.nextInt(); | |
for(int a0 = 0; a0 < t; a0++){ | |
String s = in.next(); | |
System.out.println(new Solution().isBalanced(s) ? "YES" : "NO"); | |
} | |
} | |
public static boolean isBalanced(String expression){ | |
Stack<Character> s = new Stack<Character>(); | |
for(char c : expression.toCharArray()){ | |
if(c == '{' || c == '[' || c=='(') s.push(c); | |
switch(c){ | |
case ']' : if(!s.isEmpty() && s.pop() == '[') continue; else return false; | |
case '}' : if(!s.isEmpty() && s.pop() == '{') continue; else return false; | |
case ')' : if(!s.isEmpty() && s.pop() == '(') continue; else return false; | |
} | |
} | |
return s.isEmpty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment