- Total Accepted: 202731
- Total Submissions: 611689
- Difficulty: Easy
- Contributor: LeetCode
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.
Subscribe to see which companies asked this question.
Have you met this question in a real interview?
题目:判断给出的string中,括号是否匹配。
思路:
用一个Stack来存储括号, 主要考察对栈数据结构的操作。算法的时间复杂度是O(n),空间复杂度也是O(n)。遍历传入的String s,如果遇到左括号就入栈;如果遇到右括号,检查栈如果为空,证明不能匹配,如果栈不空,pop出栈顶的元素,看是否与当前的右括号匹配。如果匹配,继续向下进行新一轮的循环,如果不匹配,返回false.
源代码:public class Solution {
public boolean isValid(String s) {
if(s.length() == 0 || s.length() == 1){
return false;
}
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++){
char cur = s.charAt(i);
if(cur == '(' || cur == '{' || cur == '['){
stack.push(cur);
}else{
switch(cur){
case ')':
if(stack.isEmpty() || stack.pop() != '('){
return false;
}
break;
case ']' :
if(stack.isEmpty() || stack.pop() != '['){
return false;
}
break;
case '}' :
if(stack.isEmpty() || stack.pop() != '{'){
return false;
}
break;
default :
break;
}
}
}
return stack.size() == 0;
}
}