Lintcode423-Valid Parentheses-Easy
思路:
数据结构:stack。遍历整个字符串,如果遇到左向括号( [ { 则入栈。如果遇到右向括号时,先检查栈是否为空,为空说明左右向括号数目不一致,返回false;不为空则弹出栈顶元素查看是否和右向括号匹配。遍历完,要return stack.isEmpty(); 确保栈内没有剩余。
代码:
public class Solution { /** * @param s: A string * @return: whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { Stack<Character> st = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') { st.push(c); } if (c == ')' || c == ']' || c == '}') { if (st.isEmpty()) { return false; } char popChar = st.pop(); if ( c == ')' && popChar != ')') { return false; } if ( c == ']' && popChar != ']') { return false; } if ( c == '}' && popChar != '}' ) { return false; } } } return st.isEmpty(); } }
代码风格优化:String遍历每一个char(line 9) ; 用if-else分支更准确(line 10, 12)
1 public class Solution { 2 /** 3 * @param s: A string 4 * @return: whether the string is a valid parentheses 5 */ 6 public boolean isValidParentheses(String s) { 7 Stack<Character> st = new Stack<Character>(); 8 9 for (Character c : s.toCharArray()) { 10 if (c == '(' || c == '[' || c == '{') { 11 st.push(c); 12 } else { 13 if (st.isEmpty()) { 14 return false; 15 } 16 char popChar = st.pop(); 17 if ( c == ')' && popChar != '(') { 18 return false; 19 } 20 if ( c == ']' && popChar != '[') { 21 return false; 22 } 23 if ( c == '}' && popChar != '{') { 24 return false; 25 } 26 } 27 } 28 return st.isEmpty(); 29 } 30 }