
LeetCode p20 Valid Parentheses 题解
1.题目:
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.
题意:
判断一个字符串内的所有括号是否搭配得当。
2.解题思路:
使用栈匹配
3.代码
[title] [] [url] [link text]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); String x = "([{"; String y = ")]}"; for (char a : s.toCharArray()) { if (stack.size() != 0) { int i = x.indexOf(stack.peek()); if (i < 0) return false; if (i == y.indexOf(a)) { stack.pop(); } else { stack.add(a); } } else { stack.add(a); } } return stack.size() == 0 ? true : false; } }
|
4.一些总结:
近期评论