Created
November 17, 2019 20:29
-
-
Save thexande/c7380130863db50e47b317a901af43a8 to your computer and use it in GitHub Desktop.
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
let test = "abba" | |
class Solution { | |
func expandPalindrome(input: String, startIndex: Int, endIndex: Int) -> (Int, Int) { | |
var start = startIndex | |
var end = endIndex | |
let inputArray = Array(input) | |
var result = (start, end) | |
repeat { | |
result = (start, end) | |
start -= 1 | |
end += 1 | |
} while start >= 0 && end < input.count && inputArray[start] == inputArray[end] | |
return result | |
} | |
func countSubstrings(_ s: String) -> String { | |
var output = "" | |
let arrs = Array(s) | |
s.enumerated().forEach { index, character in | |
let (start, end) = expandPalindrome(input: s, startIndex: index, endIndex: index) | |
if end - start + 1 > output.count { | |
output = String(arrs[start...end]) | |
} | |
} | |
for (index, character) in arrs.enumerated() { | |
guard String(character) == String(arrs[index + 1]) else { continue } | |
let (start, end) = expandPalindrome(input: s, startIndex: index, endIndex: index) | |
if end - start + 1 > output.count { | |
output = String(arrs[start...end]) | |
} | |
} | |
return output | |
} | |
} | |
Solution().countSubstrings(test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment