problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::longest_palindromic_substring::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static string longestPalindrome (string s)
 

详细描述

在文件 leetcode.h2458 行定义.

成员函数说明

◆ longestPalindrome()

string leetcode::longest_palindromic_substring::Solution::longestPalindrome ( string  s)
static

在文件 leetcode.cpp6584 行定义.

6584 {
6585 const int n = s.size();
6586 if(n < 2) {
6587 return s;
6588 }
6589
6590 int maxLen = 1;
6591 int begin = 0;
6592 // dp[i][j] 表示 s[i..j] 是否是回文串
6593 vector dp(n, vector<int>(n));
6594 // 初始化:所有长度为 1 的子串都是回文串
6595 for(int i = 0; i < n; i++) {
6596 dp[i][i] = 1;
6597 }
6598 // 递推开始
6599 // 先枚举子串长度
6600 for(int L = 2; L <= n; L++) {
6601 // 枚举左边界,左边界的上限设置可以宽松一些
6602 for(int i = 0; i < n; i++) {
6603 // 由 L 和 i 可以确定右边界,即 j - i + 1 = L 得
6604 const int j = L + i - 1;
6605 // 如果右边界越界,就可以退出当前循环
6606 if(j >= n) {
6607 break;
6608 }
6609
6610 if(s[i] != s[j]) {
6611 dp[i][j] = 0;
6612 } else {
6613 if(j - i < 3) {
6614 dp[i][j] = 1;
6615 } else {
6616 dp[i][j] = dp[i + 1][j - 1];
6617 }
6618 }
6619
6620 // 只要 dp[i][L] == true 成立,就表示子串 s[i..L] 是回文,此时记录回文长度和起始位置
6621 if(dp[i][j] != 0 && j - i + 1 > maxLen) {
6622 maxLen = j - i + 1;
6623 begin = i;
6624 }
6625 }
6626 }
6627 return s.substr(begin, maxLen);
6628 }

被这些函数引用 leetcode::longest_palindromic_substring::TEST().


该类的文档由以下文件生成: