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.
Subscribe to see which companies asked this question
这个就是括号匹配,用数据结构中的栈就可以解决
public class Solution {
public boolean isValid(String s) {
LinkedList<Character> linkedList=new LinkedList<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)!='('&&s.charAt(i)!='['&&s.charAt(i)!='{'){
if(linkedList.isEmpty()){
return false;
}else{
switch(linkedList.pop()){
case '(':
if(s.charAt(i)!=')')return false;break;
case '[':
if(s.charAt(i)!=']')return false;break;
case '{':
if(s.charAt(i)!='}')return false;break;
}
}
}else{
linkedList.push(s.charAt(i));
}
}
if(linkedList.isEmpty())return true;
else return false;
}
}
本文介绍了一种使用栈数据结构解决括号匹配问题的方法。针对包含圆括号、方括号及花括号的字符串,该算法能判断括号是否正确配对。文章通过具体示例展示了如何实现这一算法。
299

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



