File tree 4 files changed +34
-39
lines changed
Brute-Force String Search
BruteForceStringSearch.playground
4 files changed +34
-39
lines changed Original file line number Diff line number Diff line change 1
1
//: Playground - noun: a place where people can play
2
2
3
3
extension String {
4
- func indexOf( pattern: String ) -> String . Index ? {
5
- for i in self . startIndex ..< self . endIndex {
4
+ func indexOf( _ pattern: String ) -> String . Index ? {
5
+
6
+ for i in self . characters. indices {
6
7
var j = i
7
8
var found = true
8
- for p in pattern. startIndex ..< pattern . endIndex {
9
- if j == self . endIndex || self [ j] != pattern [ p] {
9
+ for p in pattern. characters . indices {
10
+ if j == self . characters . endIndex || self [ j] != pattern [ p] {
10
11
found = false
11
12
break
12
13
} else {
13
- j = j . successor ( )
14
+ j = self . characters . index ( after : j )
14
15
}
15
16
}
16
17
if found {
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 2
2
Brute-force string search
3
3
*/
4
4
extension String {
5
- func indexOf( pattern: String ) -> String . Index ? {
6
- for i in self . startIndex ..< self . endIndex {
7
- var j = i
8
- var found = true
9
- for p in pattern. startIndex ..< pattern. endIndex {
10
- if j == self . endIndex || self [ j] != pattern [ p] {
11
- found = false
12
- break
13
- } else {
14
- j = j. successor ( )
5
+ func indexOf( _ pattern: String ) -> String . Index ? {
6
+ for i in self . characters. indices {
7
+ var j = i
8
+ var found = true
9
+ for p in pattern. characters. indices{
10
+ if j == self . characters. endIndex || self [ j] != pattern [ p] {
11
+ found = false
12
+ break
13
+ } else {
14
+ j = self . characters. index ( after: j)
15
+ }
16
+ }
17
+ if found {
18
+ return i
15
19
}
16
- }
17
- if found {
18
- return i
19
- }
20
20
}
21
21
return nil
22
22
}
Original file line number Diff line number Diff line change @@ -28,21 +28,21 @@ Here is a brute-force solution:
28
28
29
29
``` swift
30
30
extension String {
31
- func indexOf (pattern : String ) -> String .Index ? {
32
- for i in self .startIndex ..< self .endIndex {
33
- var j = i
34
- var found = true
35
- for p in pattern.startIndex ..< pattern.endIndex {
36
- if j == self .endIndex || self [j] != pattern[p] {
37
- found = false
38
- break
39
- } else {
40
- j = j.successor ()
31
+ func indexOf (_ pattern : String ) -> String .Index ? {
32
+ for i in self .characters .indices {
33
+ var j = i
34
+ var found = true
35
+ for p in pattern.characters .indices {
36
+ if j == self .characters .endIndex || self [j] != pattern[p] {
37
+ found = false
38
+ break
39
+ } else {
40
+ j = self .characters .index (after : j)
41
+ }
42
+ }
43
+ if found {
44
+ return i
41
45
}
42
- }
43
- if found {
44
- return i
45
- }
46
46
}
47
47
return nil
48
48
}
You can’t perform that action at this time.
0 commit comments