LeetCode in Swift: Reverse Words in a String

Problem Statement

Given an input string, reverse the string word by word.

For example:
Given s = “ the sky is blue”,
return “ blue is sky the”.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

Original LeetCode problem page

My Solution in Swift

My first version uses a bunch of Swift built-in functions

My second version does all the works myself

The first version runs faster (284 ms vs 386 ms). The second version is slowed down by character comparison on line 12. There, I convert the character to be compared from Character to String type first. If I did the comparison directly using Character type, i.e.  c == " " , it is even slower (608 ms vs 386 ms). I guess the slow character comparison in Swift is due to its unicode support and the fact that each Character instance is an extended grapheme cluster instead of a simple ASCII integer. Hope Apple can improve the speed of this in the future.

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Reverse Words in a String268.937ms Save  (1878) Save  (1796)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift