π‘ LeetCode 20 - Valid Parentheses
π‘ LeetCode 20 - Valid Parentheses
λ¬Έμ
Given a string s 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.
- Every close bracket has a corresponding open bracket of the same type.
μ μΆλ ₯ μμ
β μμ 1
1
2
Input: s = "()"
Output: true
β μμ 2
1
2
Input: s = "()[]{}"
Output: true
β μμ 3
1
2
Input: s = "(]"
Output: false
β μμ 4
1
2
Input: s = "([])"
Output: true
μ μ½μ‘°κ±΄
1 <= s.length <= 104
- s consists of parentheses only β()[]{}β.
μμ± μ½λ
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
class Solution {
public boolean isValid(String s) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
List<Character> cList = new ArrayList<>();
Map<Character, Character> solutionMap = new HashMap();
// 2. 쑰건 ν΄μλ§΅ μ μ₯
solutionMap.put('(', ')');
solutionMap.put('{', '}');
solutionMap.put('[', ']');
// 3. λ¬Έμμ΄ μννλ©° μ€νμ μ μ¬ λ° μ κ±°
int length = 0;
for (int i=0; i<s.length(); i++) {
cList.add(s.charAt(i));
length = cList.size();
if (length > 1 && solutionMap.get(cList.get(length - 2)) == cList.get(length - 1)) {
cList.remove(cList.size() - 1);
cList.remove(cList.size() - 1);
}
}
// 4. λ°ν
return cList.size() == 0 ? true : false;
}
}
- μ½λκ° μ§μ λΆνκ³ ,
Runtime
μ μ€μ΄κ³ μ μ½λλ₯Ό κ°μ ν΄λ³΄μλ€.
κ°μ μ½λ
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
class Solution {
public boolean isValid(String s) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
Deque<Character> cDeque = new ArrayDeque<>();
Map<Character, Character> solutionMap = new HashMap();
// 2. 쑰건 ν΄μλ§΅ μ μ₯
solutionMap.put(')', '(');
solutionMap.put('}', '{');
solutionMap.put(']', '[');
// 3. λ¬Έμμ΄ μννλ©° μ€νμ μ μ¬ λ° μ κ±°
for (char c : s.toCharArray()) {
if (!cDeque.isEmpty() && solutionMap.containsKey(c)) {
if (solutionMap.get(c) == cDeque.peek()) {
cDeque.pop();
} else {
// λ¬Έμ 쑰건μ λΆν©νμ§ μλλ€λ©΄ μ μ¬
cDeque.push(c);
}
} else {
// λ±μ΄ λΉμκ±°λ λ«λ κ΄νΈλΌλ©΄ μ μ¬
cDeque.push(c);
}
}
// 4. λ°ν
return cDeque.isEmpty();
}
}
List
μ λ°μ΄ν° μΆκ° μ λ°°μ΄ λ³΅μ¬κ° μΌμ΄λ μ μμΌλ―λ‘Deque
μλ£κ΅¬μ‘° μ¬μ©for-each
λ¬Έ μ¬μ©
νκ³
peekLast()
κ° λ§¨ λ€ μμ κ°μ μΆμΆνλ€κ³ νμ¬top
κ°μ κ°μ Έμ€λ μ€ μμλλ°, μκ³ λ³΄λbottom
κ°μ κ°μ Έμ€λ λ©μλμλ€.Stack
μ μ μ νμΆμ΄λ―λ‘ μ ꡬ κΈ°μ€μΌλ‘last
λbottom
μ΄κ³ ,first
λtop
μ μλ―Ένλ€.- μ¦
Stack
μtop
μμ κ°μ μ κ±°νμ§ μκ³ μΆμΆνλ €λ©΄peek()
λ©μλλ₯Ό μ¬μ©νλ©΄ λλ€.Β
This post is licensed under CC BY 4.0 by the author.