harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[5] Longest Palindromic Substring #88

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago

暴力解 ... 5.02%

var longestPalindrome = function(s) {
    let maxLength = 0
    let ans = 0
    let index = 0

    while(index < s.length && s.length - index > maxLength) {
      for (let j = s.length - 1; j >= index; j--) {
        if (s[index] === s[j]) {
          let substr = s.slice(index, j + 1)

          if (substr === reverse(substr) && substr.length > maxLength) {
            maxLength = substr.length
            ans = substr
          }
        }
      }
      index++
    }
    return ans
};

function reverse(str) {
  return str.split('').reverse().join('')
}

57.20%

var longestPalindrome = function(s) {
    let ans = ''

    for (let i = 0; i < s.length; i++) {
        let strOdd = search(i, i)
        let strEven = search(i, i + 1)
        ans = strOdd.length > ans.length ? strOdd : ans
        ans = strEven.length > ans.length ? strEven : ans
    }

    return ans

    function search(left, right){        
        while(s[left] === s[right] && (s[left] || s[right])) {
            left--
            right++
        }
        return s.slice(left + 1, right)
    }
};
harrytothemoon commented 3 years ago
var longestPalindrome = function(s) {
    let n = s.length
    for (let k = 0; k < n; k++) {
        let right = n - 1 - k;
        let left = 0;
        while (right < n) {
            if (isPalindrome(left, right)) return s.substring(left, right + 1);
            left++
            right++
        }
    }
    return s;

    function isPalindrome(i, j) {
        while (i < j) {
            if (s[i] !== s[j]) return false
            i++
            j--
        }
        return true;
    }
};