题目:
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
题意:
给定一个字串,其中只包括以下几个字符符号,'(', ')', '{', '}', '[' and ']',我们需要判断一个字串是不是一个合理的匹配
( 和 ) 对应 { 和 }对应 [ 和 ]对应 ,对应的顺序也有要求,中间不能穿插的不对,上面举了几个例子
解法:
这个字符串匹配首先就可以想到使用 栈的结构,每当一个左边的括号进栈,在之后如果顺序正确,当它弹出的时候正好会遇到右括号。
例如 (){[]}
第一步 ( 如栈 栈为

第二步 遇到右括号 ) pop栈 得到 ( 匹配
第三步 { 如栈 第四步 [如栈 栈变为

第五部 遇到右括号 ] pop栈得到 [ 匹配
第六步 遇到 } pop栈得到 { 匹配成功
最后字符串匹配完毕 ,栈为空 ,该字串可以返回true
代码:
class Solution {
public boolean isValid(String s) {
int type=0;
int length=s.length();
if(length%2!=0) return false;
Stack stack = new Stack();
if(length==0) return true;
else stack.push(s.charAt(0));
for(int i=1;i<length;i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
stack.push(s.charAt(i));
}
else{
if(s.charAt(i)==')'){
if(stack.pop().toString().charAt(0)!='(') return false;
}
else if(s.charAt(i)=='}'){
if(stack.pop().toString().charAt(0)!='{') return false;
}
else{
if(stack.pop().toString().charAt(0)!='[') return false;
}
}
}
if(stack.size()==0)
return true;
else return false;
}
}
改进: 减少一定的代码量
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
223

被折叠的 条评论
为什么被折叠?



