Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
Constraints:
풀이코드
import java.util.*;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i=0; i<s.length(); i++) {
if (stack.isEmpty()) {
stack.push(s.charAt(i));
} else if (stack.peek() == '(' && s.charAt(i) == ')') {
stack.pop();
} else if (stack.peek() == '{' && s.charAt(i) == '}') {
stack.pop();
} else if (stack.peek() == '[' && s.charAt(i) == ']') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
return stack.isEmpty();
}
}
풀이방법
괄호(특수문자)를 주고 여는 괄호와 닫는괄호가 만나면 괄호는 지워지며, 그렇게 지워서 남은 괄호가 없으면 true 남은 괄호가 있으면 false를 return 하는 문제이다.
[LeetCode] 1700. Number of Students Unable to Eat Lunch (0) | 2021.11.07 |
---|---|
[LeetCode] 71. Simplify Path (0) | 2021.11.07 |
[LeetCode] Running Sum of 1d Array (0) | 2021.05.01 |
[LeetCode] Two Sum (0) | 2021.04.27 |