File tree Expand file tree Collapse file tree 4 files changed +34
-39
lines changed
Brute-Force String Search
BruteForceStringSearch.playground Expand file tree Collapse file tree 4 files changed +34
-39
lines changed Original file line number Diff line number Diff line change 11//: Playground - noun: a place where people can play
22
33extension 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 {
67 var j = i
78 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] {
1011 found = false
1112 break
1213 } else {
13- j = j . successor ( )
14+ j = self . characters . index ( after : j )
1415 }
1516 }
1617 if found {
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 22 Brute-force string search
33*/
44extension 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
1519 }
16- }
17- if found {
18- return i
19- }
2020 }
2121 return nil
2222 }
Original file line number Diff line number Diff line change @@ -28,21 +28,21 @@ Here is a brute-force solution:
2828
2929``` swift
3030extension 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
4145 }
42- }
43- if found {
44- return i
45- }
4646 }
4747 return nil
4848 }
You can’t perform that action at this time.
0 commit comments