【20】Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
题译:
给定一个只包含字符’(’,’)’,’{‘,’}’,’[‘和’]’的字符串,确定输入字符串是否有效。
括号必须以正确的顺序关闭,“()”和“()[] {}”都有效,但“(]”和“([]]”不是。
Solution:
public class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>();
for(char c : s.toCharArray()){
if(c=='(')
st.push(')');
else if(c=='{')
st.push('}');
else if(c=='[')
st.push(']');
else if(st.empty()||st.pop()!=c)
return false;
}
return st.empty();
}
}
心得:
1、String.toCharArray()将String转换成char[];
2、for(char c : charArray)语法;
3、Stack的使用。