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

Kafka — All you want to know

A simple PHP framework (6/?) Templating

My 3-days experience using Github Copilot: surprisingly smart!

Github Copilot logo is a cute flight copilot.

There must be limits!

Released Behavior library for Xamarin.Forms

Install fully Flutter on Ubuntu

Agile for Productivity — Part 2: Minimize interruptions, maximize flow

Agile for Productivity — Part 2: Minimize interruptions, maximize flow

Collecting the Garbage: A brief history of GC over Android versions

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

How to Make a Nice Side Menu for Your iOS App Using Swift 5

iOS App Development [2022]

ARKit Framework in Swift

Introduction to Swift UI