Created
August 31, 2019 00:14
-
-
Save PaulWoodIII/afb39a1d621fafc0aace02a139b61935 to your computer and use it in GitHub Desktop.
classic interview question done two ways in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// ReverseWordsInAString | |
// | |
// Created by Paul Wood on 8/30/19. | |
// Copyright © 2019 Paul Wood. All rights reserved. | |
// | |
import Foundation | |
let sentence = "Words to reverse in a String" | |
let emptySentence = "" | |
let single = "a" | |
// Not very performant but very readable | |
func reverseWords(_ input: String) -> String { | |
return input | |
.components(separatedBy: .whitespacesAndNewlines) | |
.map { (string) -> String in | |
return String(string.reversed()) | |
}.joined(separator: " ") | |
} | |
// Reverse the words In place and in O(N) String is not subscriptable so we work around it with a [Character] | |
func reverseSentence(_ input: inout [Character]) { | |
var wordStart = 0 | |
var wordEnd = 0 | |
var whitespace = 0 | |
func reverse(_ input: inout [Character], start: inout Int, end: inout Int) { | |
while start < end { | |
let temp = input[start] | |
input[start] = input[end] | |
input[end] = temp | |
start += 1 | |
end -= 1 | |
} | |
} | |
while whitespace < input.count { | |
if input[whitespace].isWhitespace { | |
reverse(&input, start: &wordStart, end: &wordEnd) | |
wordStart = whitespace + 1 | |
} | |
whitespace += 1 | |
wordEnd = whitespace - 1 | |
} | |
if whitespace != 0 { | |
reverse(&input, start: &wordStart, end: &wordEnd) | |
} | |
} | |
print(sentence) | |
print(reverseWords(sentence)) | |
print(reverseWords(emptySentence)) | |
print(reverseWords(single)) | |
var sentenceArray = sentence.map { (c) -> Character in | |
return c | |
} | |
reverseSentence(&sentenceArray) | |
print( String(sentenceArray)) | |
var singleArray = single.map { (c) -> Character in | |
return c | |
} | |
reverseSentence(&singleArray) | |
print( String(singleArray)) | |
var emptyArray: [Character] = [] | |
reverseSentence(&emptyArray) | |
print( String(emptyArray)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment