Created
January 31, 2016 16:21
-
-
Save miguelfermin/665b4964bf7be7152673 to your computer and use it in GitHub Desktop.
A simple function that returns true if two strings have the same exact characters -regardless of order- or false otherwise.
This file contains 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
func sameCharacters(string stringOne: String, string stringTwo: String) -> Bool { | |
let stringOneCharacters = stringOne.characters | |
let stringTwoCharacters = stringTwo.characters | |
// Early exit 1 | |
if stringOneCharacters.count != stringTwoCharacters.count { | |
return false | |
} | |
var charMatched = false | |
var matchedIndices = [Int](count: stringOneCharacters.count, repeatedValue: 0) | |
for charOne in stringOneCharacters { | |
for (i, charTwo) in stringTwoCharacters.enumerate() { | |
if charOne == charTwo && matchedIndices[i] == 0 { | |
charMatched = true | |
matchedIndices[i] = 1 | |
break | |
} | |
} | |
// Early exit 2 | |
if charMatched == false { | |
return false | |
} | |
charMatched = false | |
} | |
return true | |
} | |
sameCharacters(string: "hello", string: "olelh") // returns true | |
sameCharacters(string: "URLER", string: "RULEG") // returns false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment