题目
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.
另外,空字符串也是有效的。
解题思路
不管哪种括号,必须只能被相同类型的括号关闭。换种角度来思考,那就是右括号只能和最近的和自己类型相同的左括号匹配。 这样,我们再往下思考,只要把每次把最近放进去的括号匹配成功了那就是有效的字符串。我们从前往后遍历字符串,然后选择ArrayList来存储当前位置的字符:如果当前字符是任意类型的左括号,那就是将当前字符添加到ArrayList中去;若果当前字符是任意类型的右括号,那就判断它和ArrayList末尾的左括号是否匹配,如果匹配那就是把ArrayList末尾的字符删除,如果不匹配那就说明返回false。
代码
Java代码如下:
public boolean isValid(String s) {
List<Character> list = new ArrayList<>();
//空字符串也是有效
if (s.length() == 0)
return true;
//如果一开始就是右括号那就是无效字符串
if (s.charAt(0) == ')' || s.charAt(0) == ']' || s.charAt(0) == '}')
return false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
list.add(s.charAt(i));
} else {
if (s.charAt(i) == ')') {
if (list.size()!=0&&list.get(list.size() - 1) == '(') {
list.remove(list.size() - 1);
} else {
return false;
}
}
else if (s.charAt(i) == ']') {
if (list.size()!=0&&list.get(list.size() - 1) == '[') {
list.remove(list.size() - 1);
} else {
return false;
}
}
else if (s.charAt(i) == '}') {
if (list.size()!=0&&list.get(list.size() - 1) == '{') {
list.remove(list.size() - 1);
} else {
return false;
}
}
}
}
//最后list是否全部匹配,全部匹配的话那么list的大小就是0
if(list.size()!=0) return false;
return true;
}