思路:
数据结构: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)
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 (Character c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
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();
}
}