Skip to content

Commit b968188

Browse files
committed
feat: Add solution for LeetCode problem 20
1 parent 4ccd2d5 commit b968188

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//
2+
// 20. Valid Parentheses.swift
3+
// https://leetcode.com/problems/valid-parentheses/description/
4+
// Algorithm
5+
//
6+
// Created by ν™μŠΉν˜„ on 2024/05/04.
7+
//
8+
9+
import Foundation
10+
11+
final class LeetCode20 {
12+
func isValid(_ s: String) -> Bool {
13+
var stack: [Character] = []
14+
15+
for character in s {
16+
if "([{".contains(character) {
17+
stack.append(character)
18+
continue
19+
}
20+
21+
// `([{`κ°€ μ•„λ‹Œ λ‹«νžŒ κ΄„ν˜Έκ°€ λ“€μ–΄μ™”λŠ”λ° stack이 λΉ„μ–΄μžˆμœΌλ©΄ μ•ˆ 됨.
22+
if stack.isEmpty { return false }
23+
24+
// μ•„μŠ€ν‚€ κ°’μ˜ μ°¨λ₯Ό ν™œμš©ν•˜μ—¬ 1~2μ‚¬μ΄μ˜ 차이가 λ‚œλ‹€λ©΄ μ•Œλ§žμ€ 쌍.
25+
// ν•˜μ§€λ§Œ, 각 κ΄„ν˜Έμ˜ μ•„μŠ€ν‚€ 값이 3 이상 λ‚˜λŠ” κ²½μš°λŠ” μ„œλ‘œ λ§žμ§€ μ•ŠμŒ.
26+
// Swiftμ—μ„œλŠ” asciiValue ν”„λ‘œνΌν‹°μ˜ νƒ€μž…μ΄ `UInt8` 이기 λ•Œλ¬Έμ— μŒμˆ˜κ°€ μ—†μ–΄μ„œ κ°€λŠ₯ν•œ 비ꡐ!
27+
// `&-` λŠ” μ˜€λ²„ν”Œλ‘œμš° μ—°μ‚°μœΌλ‘œ, λ§Œμ•½ μ˜€λ²„ν”Œλ‘œμš°κ°€ λ‚œλ‹€λ©΄ λ¬΄μ‹œν•¨.
28+
if character.asciiValue! &- stack.last!.asciiValue! > 2 {
29+
return false
30+
}
31+
32+
stack.removeLast()
33+
}
34+
35+
return stack.isEmpty
36+
}
37+
}

0 commit comments

Comments
Β (0)