Implementing strStr() in Swift; breaking early

A simple solution — Swift

Using Swift to locate S2 in S1
Using Swift to locate S2 in S1

Walking the array — Theory

The initial strings
High level algorithm

Match iteration 1 — matching with s[0]

The initial comparison between s1 and s2, s1[0] and s2[0]

Match iteration 2 — matching with s[1]

The second comparison between s1 and s2, s1[1] and s2[0]
Comparing s1 and s2, s1[2] and s2[1]
Comparing s1 and s2, s1[3] and s2[2]

Match iteration 3 — matching with s1[2]

Comparing s1 and s2, s1[2] and s2[0]

Match iteration 4 — matching with s1[3]

Comparing s1 and s2, s1[3] and s2[0]
Comparing s1 and s2, s1[4] and s2[1]
Comparing s1 and s2, s1[5] and s2[2]

Things to know — Don’t go too far

It does not make sense to check beyond the end of the array
The last position that needs to be counted, calculated by s1.count — s2.count
Creating the main loop in Swift

A better solution — ArraySlice

Implementation of strStr using ArraySlice

Another solution — Two pointers

Implementation of strStr using two pointers

Another solution — walk the s2 array

Implementation of strStr walking the second array

stevecurtis.me

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

HIPAA Compliance in the Cloud

What Parenting and DevOps have in common

CS373 Spring 2022: Abinith Thallam: Final Entry

Make it btr(fs)

Image of an old open hdd

CSS4 Selectors: What Can We Expect?

How Can I Integrate Remote Configuration of AppGallery Connect in Flutter?

Why attend Ruby Wine conference?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Steven Curtis

Steven Curtis

stevecurtis.me

More from Medium

Unit Testing in Swift

Clean architectures: Inner and Outer-Scene layers

A Basic UISearchController (Swift Tutorial)

Build UITableView Sections With Nested Types