[LintCode] Valid Parentheses
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public boolean isValidParentheses(String s) { // Write your code here Stack<Character> st = new Stack<Character>(); if(s.length() == 0 || s == null) return false; for(int i = 0 ; i < s.length(); i++) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') st.push(s.charAt(i)); else{ if(st.isEmpty()) return false; if(s.charAt(i) == ')' && st.peek() != '(') return false; if(s.charAt(i) == ']' && st.peek() != '[') return false; if(s.charAt(i) == '{' && st.peek() != '}') return false; st.pop(); } } if(st.isEmpty()) return true; else return false; } |
Leave A Comment