题目链接: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.
思路:
用栈,easy。。
算法:
-
public boolean isMatch(char c1, char c2) {
-
if (c1 == ‘(‘ && c2 == ‘)‘)
-
return true;
-
if (c1 == ‘[‘ && c2 == ‘]‘)
-
return true;
-
if (c1 == ‘{‘ && c2 == ‘}‘)
-
return true;
-
return false;
-
}
-
-
public boolean isValid(String s) {
-
Stack<Character> stk = new Stack<Character>();
-
char c[] = s.toCharArray();
-
for (char i : c) {
-
if (!stk.isEmpty()) {
-
char t = (char) stk.pop();
-
if (!isMatch(t, i)) {
-
stk.push(t);
-
stk.push(i);
-
}
-
} else {
-
stk.push(i);
-
}
-
}
-
if (!stk.isEmpty())
-
return false;
-
else
-
return true;
-
}
【Leetcode】Valid Parentheses
原文:http://blog.csdn.net/yeqiuzs/article/details/51590938