原题网址:https://leetcode.com/problems/valid-parentheses/
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.
public class Solution {
public boolean isValid(String s) {
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 last = stack.pop();
if ((last == '(' && ch == ')') || (last == '[' && ch == ']') || (last == '{' && ch == '}')) continue;
return false;
}
}
return stack.isEmpty();
}
}
另一种实现:使用数组实现栈。
public class Solution {
public boolean isValid(String s) {
char[] sa = s.toCharArray();
int stack = 0;
for(int i=0; i<sa.length; i++) {
if (sa[i]=='(' || sa[i]=='[' || sa[i]=='{') sa[stack++] = sa[i];
else if (stack == 0) return false;
else if (sa[stack-1] != '(' && sa[i]==')') return false;
else if (sa[stack-1] != '[' && sa[i]==']') return false;
else if (sa[stack-1] != '{' && sa[i]=='}') return false;
else stack --;
}
return stack == 0;
}
}