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.
Example 1:
Input:"()"
Output:true
Example 2:
Input:"()[]{}"
Output:true
Example 3:
Input:"(]"
Output:false
Example 4:
Input:"([)]"
Output:false
Example 5:
Input:"{()}"
Output:true
题目解释:
给出一个字符串,这个字符串全部由"(",")","[","]","{","}"组成,有效的定义如下:
1.开区间必须与一个相应的关区间对应
2.开区间关闭顺序必须是有序的,最先打开的区间应该最后被关闭。
题目解法:
1.我自己的解法。看到这个自然而然的想到用栈,后进先出。然后嘛……java中的栈我不太会用,所以我用list来代替栈,实现了一个类似栈的功能。大致思路如下:循环遍历,遇到开区间,就放入到list中;遇到闭区间,就找list最末尾的字符x,如果这个字符x是相应的开区间则从list最末端移除x,否则说明不匹配;最后如果list的大小为0,则说明全部匹配,否则说明不匹配。
class Solution {
public boolean isValid(String s) {
char[] array = s.toCharArray();
List<Character> list = new ArrayList<>();
for(char c : array) {
if (c == '(' || c == '[' || c == '{' ) {
list.add(c);
}
if (c == ')' || c == ']' || c == '}') {
if (list.size() > 0) {
char x = list.get(list.size() - 1);
if ((c == ')' && x == '(') || (c == ']' && x == '[') || (c == '}' && x == '{')) {
list.remove(list.size() - 1);
} else {
return false;
}
} else {
return false;
}
}
}
if(list.size() == 0) return true;
else return false;
}
}
2.讨论区果然有人用stack来实现了,实现思路应该与我相同,但是确实少了很多行代码,代码如下:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}