Skip to content

Commit 54513f6

Browse files
committed
Refactor solutions for Valid Parentheses and Insert Interval
1 parent 26c5865 commit 54513f6

File tree

2 files changed

+34
-29
lines changed

2 files changed

+34
-29
lines changed

Diff for: Sort/InsertInterval.swift

+22-20
Original file line numberDiff line numberDiff line change
@@ -21,27 +21,29 @@
2121

2222
class InsertInterval {
2323
func insert(_ intervals: [Interval], _ newInterval: Interval) -> [Interval] {
24-
var index = 0
25-
var result: [Interval] = []
26-
var tempInterval = Interval(newInterval.start, newInterval.end)
27-
28-
while index < intervals.count && newInterval.start > intervals[index].end {
29-
result.append(intervals[index])
30-
index += 1
31-
}
32-
33-
while index < intervals.count && newInterval.end >= intervals[index].start {
34-
let minStart = min(tempInterval.start, intervals[index].start)
35-
let maxEnd = max(tempInterval.end, intervals[index].end)
36-
tempInterval = Interval(minStart, maxEnd)
37-
index += 1
24+
var res = [Interval](), insertIdx = 0
25+
26+
for (i, interval) in intervals.enumerated() {
27+
if interval.isOverlap(with: newInterval) {
28+
newInterval.start = min(newInterval.start, interval.start)
29+
newInterval.end = max(newInterval.end, interval.end)
30+
} else {
31+
if interval.end < newInterval.start {
32+
insertIdx += 1
33+
}
34+
35+
res.append(interval)
36+
}
3837
}
39-
result.append(tempInterval)
40-
41-
for i in index ..< intervals.count {
42-
result.append(intervals[i])
38+
39+
res.insert(newInterval, at: insertIdx)
40+
41+
return res
42+
}
43+
44+
extension Interval {
45+
func isOverlap(with interval: Interval) -> Bool {
46+
return start <= interval.end && end >= interval.start
4347
}
44-
45-
return result
4648
}
4749
}

Diff for: Stack/ValidParentheses.swift

+12-9
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,28 @@
77
class ValidParentheses {
88
func isValid(_ s: String) -> Bool {
99
var stack = [Character]()
10-
10+
1111
for char in s {
12-
if char == "(" || char == "[" || char == "{" {
12+
switch char {
13+
case "(", "[", "{":
1314
stack.append(char)
14-
} else if char == ")" {
15-
guard stack.count != 0 && stack.removeLast() == "(" else {
15+
case ")":
16+
if stack.popLast() != "(" {
1617
return false
1718
}
18-
} else if char == "]" {
19-
guard stack.count != 0 && stack.removeLast() == "[" else {
19+
case "]":
20+
if stack.popLast() != "[" {
2021
return false
2122
}
22-
} else if char == "}" {
23-
guard stack.count != 0 && stack.removeLast() == "{" else {
23+
case "}":
24+
if stack.popLast() != "{" {
2425
return false
2526
}
27+
default:
28+
continue
2629
}
2730
}
28-
31+
2932
return stack.isEmpty
3033
}
3134
}

0 commit comments

Comments
 (0)