We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 8c7086f + ae09477 commit 326f812Copy full SHA for 326f812
String/ShortestWayFormString.swift
@@ -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