思路:
用栈实现
写法一
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>();
if(s.length() == 0)
return true;
if(s.length() % 2 == 1)
return false;
for(char ch : s.toCharArray()){
if(ch == '('){
st.push(')');
}else if(ch == '['){
st.push(']');
}else if(ch == '{'){
st.push('}');
}else if(st.empty() || ch != st.pop()){ //ch == 右半边 ')' '}' ']'
return false;
}
}
if(st.empty()){
return true;
}
return false;
}
}
写法二
class Solution {
private static final Map<Character, Character> map = new HashMap<Character, Character>(){{
put('{', '}'); put('[', ']'); put('(', ')'); put('?','?');
}};
public boolean isValid(String s) {
if(s.length() == 0)
return false;
if(s.length() % 2 == 1)
return false;
LinkedList<Character> stack = new LinkedList<Character>(){{ add('?'); }};
for(char ch : s.toCharArray()){
if(map.containsKey(ch))
stack.addLast(ch);
else if(map.get(stack.removeLast()) != ch)
return false;
}
return stack.size() == 1;
}
}
本地测试
public class lc_20_isValid{
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>(); // 写法一: ac
if (s.length() == 0) {
return true;
}
if (s.length() % 2 == 1)
return false;
for (char ch : s.toCharArray()) {
if (ch == '(') {
st.push(')');
} else if (ch == '[') {
st.push(']');
} else if (ch == '{') {
st.push('}');
} else if (st.empty() || ch != st.pop()) { // “){”
return false;
}
}
if (st.empty()) {
return true;
}
return false;
}
public static void main(String[] args) {
lc_20_isValid match = new lc_20_isValid();
String s = "()[]{}";
// String s = "[";
// String s = "((";
// String s = "(]";
// String s = "){"; // st.empty()
System.out.println(match.isValid(s));
}
}