this is a simple problem, just use Stack to save the '(''{''[' and if the next character matches the peek, return true.
public boolean isValid(String s) {
int len=s.length();
if(len==0)return true;
Stack<Character> sta = new Stack<Character>();
sta.push(s.charAt(0));
for(int i=1;i<len;i++){
char ch = s.charAt(i);
if(ch=='('||ch=='['||ch=='{') sta.push(ch);
else{
if(sta.isEmpty())return false;
char ch1=sta.peek();
if(ch==')'&&ch1=='(') sta.pop();
else if(ch==']'&&ch1=='[') sta.pop();
else if(ch=='}'&&ch1=='{') sta.pop();
else return false;
}
}
if(sta.isEmpty()) return true;
else return false;
}
本文介绍了一种利用栈数据结构来判断字符串中括号是否正确配对的方法。通过遍历字符串并根据遇到的不同类型的左括号将其压入栈中,再通过匹配相应的右括号进行弹出操作,最终实现括号配对的有效验证。
438

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



