Leetcode最長回文子列
タイトルの説明:
文字列sを指定すると、sの中で最も長い回文サブ列が見つかります.sの最大長さは1000と仮定できます.
例1:
例2:
問題解決の考え方:
回文は中心対称なので、2文字目から中心対称かどうかを判断します.
C++コード:
文字列sを指定すると、sの中で最も長い回文サブ列が見つかります.sの最大長さは1000と仮定できます.
例1:
: "babad"
: "bab"
: "aba" 。
例2:
: "cbbd"
: "bb"
問題解決の考え方:
回文は中心対称なので、2文字目から中心対称かどうかを判断します.
C++コード:
class Solution {
public:
string longestPalindrome(string s) {
const int len = s.size();
if (len <= 1) return s; // , 1,
int start, maxLen = 0;
for (int i = 1; i < len; i++) // ,
{
// i-1,i
int low = i - 1, high = i;
while (low >= 0 && high < len && s[low] == s[high])
{
low--;
high++;
}
if (high - low - 1 > maxLen)
{
maxLen = high - low - 1;
start = low + 1;
}
// i
low = i - 1; high = i + 1;
while (low >= 0 && high < len && s[low] == s[high])
{
low--;
high++;
}
if (high - low - 1 > maxLen)
{
maxLen = high - low - 1;
start = low + 1;
}
}
return s.substr(start, maxLen);
}
};