Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
37 lines (35 loc) · 1.07 KB

File metadata and controls

37 lines (35 loc) · 1.07 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import java.util.HashMap;
import java.util.Stack;
/**
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 注意空字符串可被认为是有效字符串。
*/
public class Solution {
private HashMap<Character, Character> mappings;
public Solution(){
mappings = new HashMap<>();
mappings.put('}', '{');
mappings.put(')', '(');
mappings.put(']','[');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mappings.containsKey(c)) {
char topElement = stack.isEmpty()? '#': stack.pop();
if (mappings.get(c) != topElement) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.