Skip to content

Commit 326f812

Browse files
authored
Merge pull request soapyigu#351 from soapyigu/String
Add a solution to Shortest Way to Form String
2 parents 8c7086f + ae09477 commit 326f812

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

String/ShortestWayFormString.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/shortest-way-to-form-string/
3+
* Primary idea: Iterate through source and consume same characters for the target
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*/
6+
7+
class ShortestWayFormString {
8+
func shortestWay(_ source: String, _ target: String) -> Int {
9+
var res = 0, idx = 0
10+
let s = Array(source), t = Array(target)
11+
12+
while idx < t.count {
13+
let pre = idx
14+
15+
for i in 0..<s.count {
16+
if idx < t.count && t[idx] == s[i] {
17+
idx += 1
18+
}
19+
}
20+
21+
if pre == idx {
22+
return -1
23+
}
24+
25+
res += 1
26+
}
27+
28+
return res
29+
}
30+
}

0 commit comments

Comments
 (0)