【LeetCode】4.最長迴文子串

問題描述

給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。
示例 1:
輸入: “babad”
輸出: “bab”
注意: “aba” 也是一個有效答案。
示例 2:
輸入: “cbbd”
輸出: “bb”

題解

方法一、暴力法

利用循環遍歷所有子串,並判斷是否爲迴文

function longestPalindrome(s) {
  let isPlalindrome = (str) => {
    for(let i = 0, length = Math.floor(str.length / 2); i < length; i++){
      if (str.charAt(i) !== str.charAt(str.length - i -1)) {
        return false
      }
    }
    return true
  }
  let str1, result, len = 0
  if (!s) return s
  for (let i = 0, length = s.length; i < length; i++) {
    for (let j = i + 1; j < length + 1; j++) {
      str1 = s.substring(i, j)
      if (isPlalindrome(str1)) {
        if (j - i > len ) {
          result = str1
          len = j - i
        }
      }
    }
  }
  return result
}

方法二、最大公共子串

將字符串反轉與原字符串比較,求出最大公共子串,注意’adcwecda’,反轉之後公共子串不是迴文。

function longestPalindrome2(s) {
  let arr = [], maxLen = 0, end = 0
  let s1 = s.split('').reverse().join('')
  for(let i = 0, length = s.length; i < length; i++) {
    for(let j = 0; j < length; j++) {
      // 將二維數組的每一項設爲數組
      if (j == 0) arr[i] = []
      if (s.charAt(i) == s1.charAt(j)) {
        if (i == 0 || j == 0) {
          arr[i][j] = 1
        } else {
          arr[i][j] = arr[i-1][j-1] + 1
        }
      } else {
        arr[i][j] = 0
      }
      if (maxLen < arr[i][j]) {
      	// 比較倒置前後座標是否對應
        let indexRev = length - j - 1
        if (indexRev + arr[i][j] - 1 == i) {
          end = i
          maxLen = arr[i][j]
        }
      }
    }
  }
  return s.substring(end -maxLen + 1, end +1)
}

算法圖解:
在這裏插入圖片描述

方法三、擴展中心法

一個字符串其中可以有2n - 1個擴展中心, 通過不斷移動中心並進行擴展,判斷是否爲迴文,從而取得最大長度的迴文子串

在這裏插入圖片描述

var longestPalindrome = function(s) {
  if (s.length < 1) return ''
  let expandAroundCenter = (left, right) => {
    while (left >= 0 && right < s.length && s.charAt(left) == s.charAt(right)){
      left --
      right ++
    }
    return right - left - 1
  }
  let start = 0, end = 0
  for(let i = 0, length = s.length; i < length; i++) {
    const len1 = expandAroundCenter(i, i)
    const len2 = expandAroundCenter(i, i+1)
    const max = Math.max(len1, len2)
    if (max > end - start) {
   	  start = i - ((max - 1) >> 1)
      end = i + (max >> 1)
      // 或
      // start = i - Math.floor((max - 1) / 2)
      // end = i + Math.floor(max / 2)
    }
  }
  return s.substring(start,end+1)
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章