Skip to content

Commit bdf1360

Browse files
author
changhongyuan
committed
第20题
1 parent 057fe04 commit bdf1360

File tree

4 files changed

+94
-2
lines changed

4 files changed

+94
-2
lines changed

.idea/leetcode/editor.xml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
//给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
2+
//
3+
// 有效字符串需满足:
4+
//
5+
//
6+
// 左括号必须用相同类型的右括号闭合。
7+
// 左括号必须以正确的顺序闭合。
8+
//
9+
//
10+
// 注意空字符串可被认为是有效字符串。
11+
//
12+
// 示例 1:
13+
//
14+
// 输入: "()"
15+
//输出: true
16+
//
17+
//
18+
// 示例 2:
19+
//
20+
// 输入: "()[]{}"
21+
//输出: true
22+
//
23+
//
24+
// 示例 3:
25+
//
26+
// 输入: "(]"
27+
//输出: false
28+
//
29+
//
30+
// 示例 4:
31+
//
32+
// 输入: "([)]"
33+
//输出: false
34+
//
35+
//
36+
// 示例 5:
37+
//
38+
// 输入: "{[]}"
39+
//输出: true
40+
// Related Topics 栈 字符串
41+
// 👍 2043 👎 0
42+
43+
package com.changhongyuan.leetcode.editor.cn;
44+
45+
import java.text.MessageFormat;
46+
import java.util.HashMap;
47+
import java.util.Map;
48+
import java.util.Stack;
49+
50+
class ValidParentheses{
51+
//leetcode submit region begin(Prohibit modification and deletion)
52+
class Solution {
53+
public boolean isValid(String s) {
54+
if (s.length() % 2 != 0) return false;
55+
Map<Character, Character> map = new HashMap<Character, Character>();
56+
map.put('(', ')');
57+
map.put('{', '}');
58+
map.put('[', ']');
59+
Stack<Character> stack = new Stack<Character>();
60+
61+
for (int i = 0; i < s.length(); i++) {
62+
Character c = s.charAt(i);
63+
if (stack.empty()) {
64+
stack.push(c);
65+
continue;
66+
}
67+
if (c != map.get(stack.peek())) {
68+
stack.push(c);
69+
} else {
70+
stack.pop();
71+
}
72+
}
73+
return stack.empty();
74+
}
75+
}
76+
//leetcode submit region end(Prohibit modification and deletion)
77+
78+
public static void main(String[] args) {
79+
String s = "([)]";
80+
Solution solution = new ValidParentheses().new Solution();
81+
boolean isValid = solution.isValid(s);
82+
System.out.println("result is = " + isValid);
83+
}
84+
}

src/main/java/com/changhongyuan/leetcode/editor/cn/all.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

src/main/java/com/changhongyuan/leetcode/editor/cn/translation.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)