5. Longest Palindromic Substring [Medium]
Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
Analyse:
新增一個function用來回傳從位子x, y開始, 最長的palindromic string, x -=1, y +=1.
利用迴圈依次檢查單數與雙數字元的string.
Solution:
class Solution {
func longestPalindrome(_ s: String) -> String {
var chars = Array(s);
var output = "";
for i in 0..<chars.count {
var result = findPalindrome(s, i, i)
if(result.count > output.count) {
output = result
}
var result2 = findPalindrome(s, i, i + 1)
if(result2.count > output.count) {
output = result2
}
}
return output;
}
func findPalindrome(_ s: String, _ x:Int, _ y:Int) -> String {
var chars = Array(s);
var i = x;
var j = y;
var output = "";
if(i == j) {
output = String(chars[i]);
i -= 1;
j += 1;
}
while(i >= 0 && j < chars.count && chars[i] == chars[j]) {
output = String(chars[i]) + output + String(chars[j]);
// print("\(output)");
i -= 1;
j += 1;
}
return output;
}
}