题目链接:https://leetcode.com/problems/valid-parentheses/
题目:
'('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid."()"
and "()[]{}"
are all valid but "(]"
and "([)]"
思路:
用栈,easy。。
算法:
1. public boolean isMatch(char c1, char c2) {
2. if (c1 == '(' && c2 == ')')
3. return true;
4. if (c1 == '[' && c2 == ']')
5. return true;
6. if (c1 == '{' && c2 == '}')
7. return true;
8. return false;
9. }
10.
11. public boolean isValid(String s) {
12. new Stack<Character>();
13. char c[] = s.toCharArray();
14. for (char i : c) {
15. if (!stk.isEmpty()) {
16. char t = (char) stk.pop();
17. if (!isMatch(t, i)) {// 如果可以抵消
18. stk.push(t);
19. stk.push(i);
20. }
21. else {
22. stk.push(i);
23. }
24. }
25. if (!stk.isEmpty())
26. return false;
27. else
28. return true;
29. }