一、问题描述
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.
二、问题分析
使用Stack进栈、出栈操作即可实现。
三、算法代码
public class Solution {
public boolean isValid(String s) {
String left = "([{";
String right = ")]}";
Stack<Character> stack = new Stack<Character>();
char c;
for(int i = 0; i < s.length(); i++){
c = s.charAt(i);
if(left.indexOf(c) != -1){
stack.push(c);
}else{
if(stack.isEmpty() || stack.peek() != left.charAt(right.indexOf(c))){
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
}
本文介绍了一种使用栈数据结构来判断字符串中括号是否有效配对的方法。通过遍历输入字符串并利用栈进行开闭括号的匹配,可以有效地解决括号匹配问题。

318

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



