[LeetCode] 5. Longest Palindromic Substring [Medium]

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

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]);
            i -= 1;
            j += 1;
        }
        
        return output;
    }
}
   

Last updated