Skip to content

Instantly share code, notes, and snippets.

@bhakes
Last active August 20, 2019 17:44
Show Gist options
  • Save bhakes/519f11378c916d181d5b3fe10424644c to your computer and use it in GitHub Desktop.
Save bhakes/519f11378c916d181d5b3fe10424644c to your computer and use it in GitHub Desktop.
import UIKit
import XCTest
/*
Thoughts/Assumptions:
- If we are going to try to find a solution with a time complexity of O(n), we are going to have to get creative.
- We could possibly use two converging indicies, one starting from the from of the string, the other starting from the end.
- Because were taking in a String and returning a String, we could make an extension on String.
- I should consider whether or not 'y' is included as a vowel.
Test cases:
"A test string".reverseVowels() // "I test strang"
"Hello".reverseVowels() // "Holle"
"She is Happy".reverseVowels() // "Sha is Heppy"
"She is Happy".reverseVowels() // "Shy as Hippe"
"Katie".reverseVowels() // "Ketia"
"N/A".reverseVowels() // "N/A"
"".reverseVowels() // ""
Approach: Write a String extension, make a static variable of an array of vowels, and static var of an array of vowels with Y. Create a function with a boolean flag for whether not you want to use Y as a vowel. Create two indexes, one at the from of the array, and one at the back. With the first index, start looking at whether or not each index position is a vowel or not. If not, move to the next. If it is a vowel, find the first vowel starting from the back of the list, in the same way we found the vowel from the front. As long as the firstIndex < secondIndex, if second finds a vowel, swap it with the firstIndex vowel. Then start over from the first index vowel.
*/
extension String {
static let vowels: Set<Character> = ["a","e","i","o","u","A","E","I","O","U"]
static let vowelsY: Set<Character> = String.vowels.union(["y", "Y"])
func reverseVowels(_ yIsAVowel: Bool = false) -> String {
if self == "" { return "" }
var chars = Array(self)
var lhIndex = 0
var rhIndex = chars.count - 1
let vowelsToUse = yIsAVowel ? String.vowelsY : String.vowels
while lhIndex < rhIndex {
if !vowelsToUse.contains(chars[lhIndex]) {
lhIndex += 1
} else {
if !vowelsToUse.contains(chars[rhIndex]) {
rhIndex -= 1
} else {
chars.swapAt(lhIndex, rhIndex)
lhIndex += 1
rhIndex -= 1
}
}
}
return String(chars)
}
}
// Test Cases
XCTAssert("A test string".reverseVowels() == "i test strAng")
XCTAssert("Hello".reverseVowels() == "Holle")
XCTAssert("She is Happy".reverseVowels() == "Sha is Heppy")
XCTAssert("She is Happy".reverseVowels(true) == "Shy as Hippe")
XCTAssert("Katie".reverseVowels() == "Ketia")
XCTAssert("N/A".reverseVowels() == "N/A")
XCTAssert("".reverseVowels() == "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment