20. Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Input: ” {[]} ” Output: true
Input: ” ([)] ” Output: false
Input: ” ()[]{} ” Output: true
判断多种括号(){}[]是否完整配对
方法1:5ms
使用java.util.Stack
栈
每次读到前括号“ ( [ { ”时,不压入该前括号,而是向栈中压入其对应的后括号“ ) ] } ”。
这样在之后读到后括号时,就无需再额外找对应的前括号来判断是否与栈顶匹配,而是直接判断该后括号与栈顶是否相等。
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char ch : s.toCharArray()){
if (ch == '(')
stack.push(')');
else if (ch =='[')
stack.push(']');
else if (ch =='{')
stack.push('}');
else if (stack.isEmpty() || stack.pop() != ch)
return false;
}
return stack.isEmpty();
}
方法2:5ms
使用java.util.Stack
栈
与方法1不同的是,每次读到前括号“ ( [ { ”时,直接压入该前括号
public boolean isValid3(String s) {
Stack<Character> stack = new Stack<Character>();
String str1 = "({[";
String str2 = ")}]";
for (char ch : s.toCharArray()){
if (str1.indexOf(ch) != -1)
stack.push(ch);
else if (str2.indexOf(ch) != -1){
if (stack.isEmpty() || stack.peek() != str1.charAt(str2.indexOf(ch)))
return false;
else
stack.pop();
}
//else if (stack.isEmpty()||stack.pop() != str1.charAt(str2.indexOf(ch))) return false;
}
return stack.isEmpty();
}
方法3:4ms
没直接使用java的java.util.Stack栈。而是用数组来模拟栈操作
public boolean isValid2(String s) {
char[] stack = new char[s.length()];
String str1 = "({[";
String str2 = ")}]";
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (str1.indexOf(s.charAt(i)) != -1){
stack[j++] = s.charAt(i);
}
else if (str2.indexOf(s.charAt(i)) != -1){
if (j == 0 || stack[j - 1] != str1.charAt(str2.indexOf(s.charAt(i))))
return false;
else
j = j - 1;
}
}
return j == 0;
}