5.longest palindrom subsequence
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
思路:在字符串s中,以每个元素为中心点,考察元素两边的值是否为回文串,
如果相等继续扩大考察范围。如果不相等,循环跳出,指针指向元素后一位的元素,继续考察。
考察回文串的时候,要注意奇偶性。字符串下标为奇数的情况,直接往两边延伸判断。
字符串为偶数的情况,需要先判断相邻两位。再往外延伸。
var longestPalindrome = function(s) {
let left = 0;
let right = 0;
let start = 0;
let maxL = Number.MIN_VALUE;
for (let i = 0; i < s.length; i += 0.5){ //步长设为0.5
left = Math.ceil(i - 1); //步长设为0.5,用ceil和floor
right = Math.floor(i + 1);//方便奇偶index的比较。如果index是偶数,先判断相邻位置上的元素。
while (left >= 0 && right < s.length){
if (s[left] === s[right]){
left--;
right++;
} else {
break;
}
}
if (right - left - 1 > maxL){
maxL = right - left - 1; //回文串长度
start = left + 1; // 回文串起始位置
}
}
return s.slice(start, start + maxL);
}
- Palindromic Substrings
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.
Example 2:
Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.
思路:遍历给出的字符串。遍历的时候,以每个当前字符为中心,向前向后伸展。到不能得到回文串为止。然后遍历下一个字符。
遍历的过程中需要注意,当前字符的奇偶index的问题。因为,如果是奇数,那么,当前字符为中心。
如果index = 偶数,那么先考察与当前字符相邻的字符,这两个字符在一起是否为回文串。如果是,再以这两个字符为中心,
向前向后伸展。
var countSubstrings = function(s) {
if (s.length === 0) return 0;
let count = 0;
for (let i = 0; i < s.length; i++){
count = count + extendPalindrom(s, i, i);//回文串的长度是奇数,
//并且i是正中间的位置
count = count + extendPalindrom(s, i, i + 1);//回文串的长度是偶数,
// 在正中间的位置有两位,分别是 i, 和 i + 1
}
return count;
};
function extendPalindrom (str, start, end){
let count = 0;
for (let i = 0; start >= 0 && end < str.length; i++){
if (str[start] === str[end]){
start--;
end++;
count++;
}else {
break;
}
}
return count;
}
本文介绍了一种高效算法,用于在给定字符串中找到最长的回文子串。通过以每个字符为中心,向两边扩展来检查回文性质,算法能够处理奇数和偶数长度的回文串。
2441

被折叠的 条评论
为什么被折叠?



