LeetCode-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.
这一题是典型的使用压栈的方式解决的问题,题目中还有一种valid情况没有说明,需要我们自己考虑的,就是"({[]})"这种层层嵌套但
可以完全匹配的,也是valid的一种。解题思路是这样的:我们对字符串S中的每一个字符C,如果C不是右括号,就压入栈stack中。
如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid,非空就取出栈顶的字符pre来对比,如果是匹配
的,就弹出栈顶的字符,继续取S中的下一个字符;如果不匹配,说明不是valid的,直接返回。当我们遍历了一次字符串S后,注意
这里还有一种情况,就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,因为只要valid,一
定全都可以得到匹配使左括号弹出。
public class Solution { public boolean isValid(String s) { Stack<Character> stack=new Stack<Character>(); for (int i=0 ; i<s.length(); i++){ char c=s.charAt(i); if(c == '(' || c == '[' || c == '{'){ stack.push(c); } else if(c == ')' || c == ']' || c == '}'){ if(stack.empty()){ return false; } else{ if ((c == ')' && stack.peek() == '(') || (c == ']' && stack.peek() == '[') || (c == '}' && stack.peek() == '{')){ stack.pop(); } else{ return false; } } } } if(!stack.empty()){ return false; } else{ return true; } } }
二刷:
class Solution {
public boolean isValid(String s) {
if(s==null || s.length() % 2 != 0){
return false;
}
Stack<Character> stack = new Stack<>();
boolean res = true;
for(char c: s.toCharArray()){
if(c == '(' || c == '[' || c == '{'){
stack.push(c);
}
else if(c == ')' || c == ']' || c == '}'){
if(stack.isEmpty()){
res = false;
break;
}
else if(c == ')' && stack.pop() != '('){
res = false;
break;
}
else if(c == ']' && stack.pop () != '['){
res = false;
break;
}
else if(c == '}' && stack.pop() != '{'){
res = false;
break;
}
}
}
if(!stack.isEmpty()){
res=false;
}
return res;
}
}
posted on 2016-04-29 23:00 IncredibleThings 阅读(157) 评论(0) 收藏 举报
浙公网安备 33010602011771号