题目

题目地址:https://leetcode-cn.com/problems/valid-parentheses/

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

1
2
输入: "()"
输出: true

示例 2:

1
2
输入: "()[]{}"
输出: true

示例 3:

1
2
输入: "(]"
输出: false

示例 4:

1
2
输入: "([)]"
输出: false

示例 5:

1
2
输入: "{[]}"
输出: true

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.jarome.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class SolutionValidBrace {

Map<String, String> right = new HashMap<>();

public SolutionValidBrace() {
right.put("(", ")");
right.put(")", "(");
right.put("{", "}");
right.put("}", "{");
right.put("[", "]");
right.put("]", "[");
}

public boolean isValid(String s) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
String str = String.valueOf(s.charAt(i));
if (!stack.isEmpty()) {
String peek = stack.peek();
String peekRight = right.get(peek);
if (str.equals(peekRight)) {
stack.pop();
continue;
}
}
stack.push(str);

}
return stack.isEmpty();
}

public static void main(String[] args) {
SolutionValidBrace svb = new SolutionValidBrace();
System.out.println(svb.isValid("(]"));
System.out.println(svb.isValid("([)]"));
System.out.println(svb.isValid("{[]}"));
}
}