Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlexanderBollbach/0d1debbae58e8f53c5f94c8deb2cb7dd to your computer and use it in GitHub Desktop.
Save AlexanderBollbach/0d1debbae58e8f53c5f94c8deb2cb7dd to your computer and use it in GitHub Desktop.
import Foundation
extension String {
func safeStr(i: Int) -> String {
guard i >= 0 && i < self.count else {
fatalError()
}
return String(self[self.index(self.startIndex, offsetBy: i)])
}
func safeChar(i: Int) -> Character {
guard i >= 0 && i < self.count else {
fatalError()
}
let a = self[self.index(self.startIndex, offsetBy: i)]
return a
}
func str(s: Int, e: Int) -> String {
guard s >= 0 && s < self.count else {
fatalError()
}
guard s <= e else {
fatalError()
}
return String(self[index(startIndex, offsetBy: s)...index(startIndex, offsetBy: e)])
}
}
class Solution {
var perf = 0
func longestPalindrome(_ s: String) -> String {
func ch(_ i: Int) -> String { return s.safeStr(i: i) }
var pallindrome = ""
for i in 0..<s.count {
if i == 0 {
pallindrome.append(s.safeStr(i: i))
}
if pallindrome.count == s.count {
return pallindrome
}
var left = i
var right = i
if i < pallindrome.count - 1 {
let delta = pallindrome.count - 1 - i
right += delta
left -= delta
}
while true {
perf += 1
right += 1
if right - left != 1 { // special case, middle two chars equal
left -= 1
}
// bail out for bad indices
guard left >= 0 && right < s.count else {
break
}
let rightChar = ch(right)
let leftChar = ch(left)
let oddCase = right - left == 1 && right + 1 < s.count && ch(right + 1) == leftChar
// special case for first index, odd case adds three, so we don't want to double count first
if oddCase && i == 0 {
pallindrome = String(pallindrome.dropLast())
}
if rightChar == leftChar && !oddCase {
pallindrome.append(ch(right))
} else if oddCase {
if oddCase {
pallindrome.append(ch(left))
pallindrome.append(ch(right))
pallindrome.append(ch(right + 1))
right += 1
} else {
break
}
} else {
break
}
}
}
return pallindrome
}
}
let s = Solution()
let r = s.longestPalindrome("aaaa")
//print(s.perf)
print(r)
//assert(Solution().longestPalindrome("aaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaa")
//assert(Solution().longestPalindrome("aba") == "aba")
//assert(Solution().longestPalindrome("a") == "a")
//assert(Solution().longestPalindrome("aa") == "aa")
//assert(Solution().longestPalindrome("abcde") == "a")
//assert(Solution().longestPalindrome("aaabbbaaa") == "aaabbbaaa")
//assert(Solution().longestPalindrome("FaaabbbaaaG") == "aaabbbaaa")
//assert(Solution().longestPalindrome("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
//assert(Solution().longestPalindrome("eabcb") == "bcb")
//assert(Solution().longestPalindrome("ac") == "a")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment