题目:
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.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
解题思路:
这题我是用栈做的,但遇到 ( { [ 符号就将其入栈,遇到 ) } ] 就到栈中去找匹配的符号,如果匹配就出栈,直到栈为空,否则就false。
我犯的错:
1.以前学c敲习惯了老是改不过来,java中字符串比较大小最好不要用"==",要用a.equals(b)。
java中字符串比较大小:https://blog.csdn.net/zeephom/article/details/79642523
2.基本上对于栈的操作,都要注意栈为空的问题,即下溢。栈为空时就不能pop()了。
我的代码:
class Solution {
public boolean isValid(String s) {
String[] str = s.split("");
Stack<String> ops = new Stack<String>();
for(int i=0; i<str.length; i++) {
String c = str[i];
if(c.equals("(") || c.equals("{") || c.equals("[")) ops.push(c);
else if(c.equals(")") || c.equals("}") || c.equals("]")) {
if(ops.size()==0) {ops.push(c);break;} //防止 )为第一个时栈下溢
else{
String a = ops.pop();
if(c.equals(")")&& !a.equals("(")) {ops.push(a);break;}//这里的之所以push是因为我后面用栈是否为空判断结果,所以当不匹配时,把pop()出来的再push()进去。
else if(c.equals("}")&& !a.equals("{")) {ops.push(a);break; }
else if(c.equals("]")&& !a.equals("[")) {ops.push(a);break;}
}
}
}
if(ops.size()==0) {
return true;
}else{
return false;
}
}
}
结果:
Runtime: 10 ms, faster than 5.03% of Java online submissions for Valid Parentheses.
Memory Usage: 36.9 MB, less than 35.30% of Java online submissions for Valid Parentheses.