0%

Leetcode20 Valid Parentheses

Leetcode20 Valid Parentheses

题目描述

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
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 
determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

思路

每一个]对应一个[,一个}对应一个{,一个)对应一个(,将对应关系放入map中。
遍历字符串中的字符,如果是{([,那么将该字符放入stack中,
如果不是,应当与栈顶元素进行匹配,通过map找到对应的字符,然后与栈顶元素进行匹配。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public boolean isValid(String s) {
// if(s.length()==1) return false;
Stack<Character> stack = new Stack<>();
HashMap<Character,Character> map = new HashMap<>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[')
stack.add(s.charAt(i));
else if(stack.empty()||map.get(s.charAt(i))!=stack.peek()){
return false;
}else{
stack.pop();
continue;
}
}
if(stack.empty())
return true;
return false;
}
}
-------------本文结束感谢您的阅读-------------

Welcome to my other publishing channels