Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.題目的意思是輸入一個字符串,咱們要找到這個字符串的最長的知足迴文條件的子字符串。
迴文的意思就是反轉字符串後和原字符串相等。javaExample:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"code
private int maxLen,low; public String longestPalindrome(String s){ int length = s.length(); if(length < 2)return s; for(int i=0;i<length-1;i++){ extendPalindorme(s,i,i); extendPalindorme(s,i,i+1); } return s.substring(low,low+maxLen); } public void extendPalindorme(String s,int begin,int end){ while(begin >= 0 && end < s.length() && (s.charAt(begin)== s.charAt(end))){ begin --; end ++; } if(maxLen < end-begin-1){ low = begin+1; maxLen = end-begin-1; } }
/** * @param {string} s * @return {string} */ var maxLen = 0; var low = 0; var longestPalindrome = function(s) { var length = s.length; if(length < 2){ return s; } for(var i=0;i<length-1;i++){ extendPalindrome(s,i,i); extendPalindrome(s,i,i+1); } let res = s.substring(low,low+maxLen); low =0;maxLen= 0; return res; }; function extendPalindrome(s,start,end){ while(start >= 0 && end < s.length && (s[start] == s[end])){ start --; end ++; } if(maxLen < end-start - 1){ low = start + 1; maxLen = end-start-1; } }