Skip to content

Commit e8c5a7b

Browse files
committed
Optimize solution to Decode String
1 parent 1fa48a4 commit e8c5a7b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@
148148
[Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)| [Swift](./Stack/PreorderTraversal.swift)| Medium| O(n)| O(n)|
149149
[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)| [Swift](./Stack/InorderTraversal.swift)| Medium| O(n)| O(n)|
150150
[Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [Swift](./Stack/PostorderTraversal.swift)| Hard| O(n)| O(n)|
151+
[Decode String](https://leetcode.com/problems/decode-string/)| [Swift](./Stack/DecodeString.swift)| Medium| O(n)| O(n)|
151152

152153

153154
## Tree

Stack/DecodeString.swift

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/decode-string/
3+
* Primary idea: Primary idea is to maintain two stacks[i.e. countStack and characterStack].
4+
* Traverse the given string and process the elements into the respective stacks, and accordingly update the result.
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
10+
class Solution {
11+
func decodeString(_ s: String) -> String {
12+
var result = ""
13+
var countStack = [Int]()
14+
var characterStack = [String]()
15+
let allowedDigits = Set(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
16+
var arrayString = Array(s), i = 0
17+
18+
while i < arrayString.count{
19+
20+
if allowedDigits.contains(String(arrayString[i])){
21+
22+
var count = 0
23+
while allowedDigits.contains(String(arrayString[i])){
24+
count = 10 * count + Int(String(arrayString[i]))!
25+
i += 1
26+
}
27+
countStack.append(count)
28+
}else if arrayString[i] == "["{
29+
30+
characterStack.append(result)
31+
result = ""
32+
i += 1
33+
}else if arrayString[i] == "]"{
34+
35+
if var temp = characterStack.popLast(), let repeatTime = countStack.popLast(){
36+
37+
for _ in 0..<repeatTime{
38+
temp.append(result)
39+
}
40+
result = temp
41+
}
42+
i += 1
43+
}else{
44+
45+
result.append(arrayString[i])
46+
i += 1
47+
}
48+
}
49+
50+
return result
51+
}
52+
}

0 commit comments

Comments
 (0)