Given a string s
, find s
the longest palindromic substring in .
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also the answer to the question.
Example 2:
Input: s = "cbbd"
Output: "bb"
hint:
1 <= s.length <= 1000
s consists of numbers and letters only
This question really can't be done without looking at the idea. . .
- understand the meaning of the question
- Title Given a string
- We need to find the longest palindrome in this string
- Palindrome: A string that reads the same forwards and backwards
- the whole idea
- I solve the problem based on a core idea of the palindrome: spread from the center point to both sides to find the palindrome string. This direction is equivalent to enumerating every point as the center point.
- If the palindrome string is odd, such as "bab", its center point has only one "a", so it spreads from "a" to both sides
- If the palindrome string is even, such as "baab", its center point has two "aa", so it spreads from "aa" to both sides
- Write an auxiliary function to find the palindrome string, call the auxiliary function when the center point is determined, and directly return the found palindrome string
- Compare the palindrome string found each time with the previous one, and keep whoever is longer
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let str = ""
for(let i=0; i<s.length; i++){//abba
//穷举中心点
let subString1 = findHuiWen(s,i,i)
let subString2 = findHuiWen(s,i,i+1)
str = str.length > subString1.length ? str : subString1
str = str.length > subString2.length ? str : subString2
}
return str
};
function findHuiWen(s, left, right){
while(left >=0 && right < s.length) {
if(s.charAt(left) == s.charAt(right)) {
left--
right++
} else {
break
}
}//执行结束left和right都回退一个,但是substring方法左闭右开[,),因此right保持不变
return s.substring(left+1,right)
}
Knowledge points used:
String.prototype.charAt()
The charAt() method returns the specified character from a string.
str.charAt(index)
String.prototype.substring()
substring()
method returns a subset of a string between the start index and the end index, or a subset from the start index until the end of the string.
str.substring(indexStart[, indexEnd])