Skip to content

Instantly share code, notes, and snippets.

@bradleyyin
Created August 21, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradleyyin/0c13b57ff60effa201fd253b3322fab8 to your computer and use it in GitHub Desktop.
Save bradleyyin/0c13b57ff60effa201fd253b3322fab8 to your computer and use it in GitHub Desktop.
code challenge AH 8
"Challenge 8: String is rotated
Difficulty: Tricky
Write a function that accepts two strings, and returns true if one string is rotation of the other, taking letter case into account.
Tip: A string rotation is when you take a string, remove some letters from its end, then append them to the front. For example, "swift" rotated by two characters would be "ftswi".
Sample input and output
The string "abcde" and "eabcd" should return true.
The string "abcde" and "cdeab" should return true.
The string "abcde" and "abced" should return false; this is not a string rotation.
The string "abc" and "a" should return false; this is not a string rotation.
"
Excerpt From: Paul Hudson. "Swift Coding Challenges." Apple Books.
func checkRotation(string1: String, string2: String) -> Bool {
guard string1.count == string2.count else {
return false
}
let count = string1.count
var string = string1
for i in 1...count {
string.removeLast()
string.insert(string1[string1.index(string1.endIndex, offsetBy: (i * -1))], at: string.index(string.startIndex, offsetBy: 0))
if string == string2 {
return true
}
}
return false
}
checkRotation(string1: "abcde", string2: "eabcd")
checkRotation(string1: "abcde", string2: "cdeab")
checkRotation(string1: "abcde", string2: "abced")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment