leetCode刷题(找到最长的回文字符串)

时间:2022-06-01
本文章向大家介绍leetCode刷题(找到最长的回文字符串),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequenceand not a substring.

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
  var maxLength="";
  var maxPalindrome="";
  for(index=0;index<s.length;index++){
      var strOdd=getPalindromeLength(index,index,s);
      var strEven=getPalindromeLength(index,index+1,s);
      var strOddLength=strOdd.length;
      var strEvenLength=strEven.length;
      if(maxLength<strOddLength){
          maxLength=strOddLength;
          maxPalindrome=strOdd;
      }
      if(maxLength<strEvenLength){
          maxLength=strEvenLength;
          maxPalindrome=strEven;
      }
  }
  function getPalindromeLength(start,end,Palindrome){
      while((start>=0)&&(end<Palindrome.length)&&(Palindrome[start]==Palindrome[end])){
            start--;
            end++;
      }
      return Palindrome.substring(start+1,end);
  }
  return maxPalindrome
};