力扣20
https://leetcode-cn.com/problems/valid-parentheses/
之前的文章说过这种括号匹配的题目一般都是栈做,但是笔试的话为了追求效率,可以考虑用一些字符串api
巧妙的字符串替换(不推荐)
1 2 3 4 5 6 7 8 9 10 11
|
public boolean isValid(String s) { while (s.contains("()") || s.contains("[]") || s.contains("{}")){ s = s.replace("()", ""); s = s.replace("[]", ""); s = s.replace("{}", ""); } return s.length() == 0; }
|
巧妙的栈做法(推荐),这个栈设计的很巧妙,写起来比字符串替换更简单,推荐
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public boolean isValid(String s) { char[] chars = s.toCharArray(); Deque<Character> stack = new LinkedList<>(); for (char c : chars) { if (c == '{') stack.offerLast('}'); else if (c == '[') stack.offerLast(']'); else if (c == '(') stack.offerLast(')'); else while (stack.isEmpty() || stack.pollLast() != c) return false; } return stack.isEmpty(); }
|
其他字符串类型的题目可以点击这里