Given a string s 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.
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
括号是否匹配的问题。而且字符串s中只有括号,没有其他字符。
思路:
典型的stack问题。
遇到"(", “[”, "{“压栈,遇到“)” “]”, "}"就看栈顶是不是与之对应的括号,出栈,如果这时栈为空或者不匹配,返回false。
最后如果栈为空,说明完全匹配,返回true。
public boolean isValid(String s) {
if(s.length() < 2) return false;
HashMap<Character, Character> map = new HashMap<>();
Stack<Character> stack = new Stack<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
for(int i = 0; i < s.length(); i ++) {
char ch = s.charAt(i);
if(map.containsKey(ch)) {
stack.push(ch);
} else {
if(stack.isEmpty() ||
ch != map.get(stack.pop())) return false;
}
}
return (stack.isEmpty());
}
也可以不用map,直接比较各括号,但是会慢一点
public boolean isValid(String s) {
if(s.length() < 2) return false;
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i ++) {
char ch = s.charAt(i);
if(ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else {
if(stack.isEmpty()) return false;
char pair = stack.pop();
if((ch == ')' && pair != '(') ||
(ch == ']' && pair != '[') ||
(ch == '}' && pair != '{')) return false;
}
}
return (stack.isEmpty());
}
用数组模拟栈会很高效。
public boolean isValid(String s) {
int n = s.length();
int[] st = new int[n];
int head = -1;
for(int i = 0; i < n; i++) {
if(head == -1) {
st[++head] = s.charAt(i); //if stack.isEmpty(){stack.add(ch)}
continue;
}
char ch = s.charAt(i);
if(ch == ')') {
if(st[head] != '(') return false;
head--;
} else if(ch == ']') {
if(st[head] != '[') return false;
head--;
} else if(ch == '}') {
if(st[head] != '{') return false;
head--;
} else {
st[++head] = ch;
}
}
return (head == -1);
}