Skip to content

Instantly share code, notes, and snippets.

@crised
Created November 26, 2015 14:45
Show Gist options
  • Save crised/229172d6126b1c30c304 to your computer and use it in GitHub Desktop.
Save crised/229172d6126b1c30c304 to your computer and use it in GitHub Desktop.
class Solution {
public Solution() {
String YES = "{[()()]}";
//String NO = "([)()]";
String NO = ")(";
// System.out.println(solution(YES));
System.out.println(solution(NO));
}
public int solution(String S) {
int n = S.length();
if (n == 0) return 1;
char[] stack = new char[n + 1]; //n+1, top++!!
int top = 0;
for (int i = 0; i < n; i++) {
char c = S.charAt(i);
//push
top++;
stack[top] = c;
//checkifPop
if (top < 1) continue;
if (stack[top] == ')' && stack[top - 1] == '(') top = top - 2;
if (stack[top] == ']' && stack[top - 1] == '[') top = top - 2;
if (stack[top] == '}' && stack[top - 1] == '{') top = top - 2;
}
if (top == 0) return 1;
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment