---
# System prepended metadata

title: 0020. Valid Parentheses
tags: [Leetcode, FaceBook, Easy, Parentheses]

---

# 0020. Valid Parentheses
###### tags: `Leetcode` `Easy` `FaceBook` `Parentheses`
Link: https://leetcode.com/problems/valid-parentheses/
## 思路
用stack解
## Code
### 思路一
```java=
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < s.length();i++){
            char c = s.charAt(i);
            if(c=='('||c=='['||c=='{'){
                stack.add(c);
            }
            else{
                if(stack.isEmpty()) return false;
                if(stack.peek()=='(' && c!=')'){
                    return false;
                }
                else if(stack.peek()=='[' && c!=']'){
                    return false;
                }
                else if(stack.peek()=='{' && c!='}'){
                    return false;
                }
                else{
                    stack.pop();
                }
            }
        }
        if(stack.isEmpty()) return true;
        else return false;
    }
}
```
### 思路二
```java=
public boolean isValid(String s) {
	Stack<Character> stack = new Stack<Character>();
	for (char c : s.toCharArray()) {
		if (c == '(')
			stack.push(')');
		else if (c == '{')
			stack.push('}');
		else if (c == '[')
			stack.push(']');
		else if (stack.isEmpty() || stack.pop() != c)
			return false;
	}
	return stack.isEmpty();
}
```