Post

πŸ’‘ 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:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. 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.