当前位置: 首页 > article >正文

用100道题拿下你的算法面试(字符串篇-8):回文子串数目

一、面试问题给定一个字符串s求出该字符串中长度大于或等于 2的所有回文子串的总数量。若一个子串正读与反读完全相同则该子串为回文子串。示例 1输入s abaab输出3解释长度大于 1 的回文子串为aba、aa、baab。示例 2输入s aaa输出3解释长度大于 1 的回文子串为aa、aa、aaa。示例 3输入s abbaeae输出4解释长度大于 1 的回文子串为bb、abba、aea、eae。二、【暴力解法】枚举所有可能子串 —— 时间复杂度 O(n³)空间复杂度 O(1)(一) 解法思路核心思路通过两层嵌套循环枚举所有可能的子串并逐一判断每个子串是否为回文。(二) 使用 5 种语言实现1. C// C 程序通过枚举所有可能子串统计字符串中长度 2 的回文子串总数 #include iostream #include string using namespace std; // 辅助函数判断子串 s[i..j] 是否为回文 bool isPalindrome(string s, int i, int j) { while (i j) { // 两端字符不相等 → 不是回文 if (s[i] ! s[j]) return false; // 向中间收缩继续判断 i; j--; } return true; } // 主函数统计长度 2 的回文子串数量 int countPS(string s) { int n s.length(); int res 0; // 记录回文子串总数 // 枚举所有起始位置 i for (int i 0; i n; i) { // 枚举所有结束位置 jj i保证长度至少为 2 for (int j i1; j n; j) { // 如果从 i 到 j 的子串是回文结果 1 if (isPalindrome(s, i, j)) res; } } return res; } // 主测试函数 int main() { string s abaab; cout countPS(s); // 输出 3 return 0; }2. Java// Java 程序通过枚举所有可能的子串统计字符串中长度 2 的回文子串数量 class DSA { // 函数判断子串 s[i..j] 是否为回文 static boolean isPalindrome(String s, int i, int j) { while (i j) { if (s.charAt(i) ! s.charAt(j)) return false; i; j--; } return true; } static int countPS(String s) { int n s.length(); // 枚举所有长度大于 1 的子串 int res 0; for (int i 0; i n; i) { for (int j i 1; j n; j) { // 如果从 i 到 j 的子串是回文结果加 1 if (isPalindrome(s, i, j)) res; } } return res; } public static void main(String[] args) { String s abaab; System.out.println(countPS(s)); // 输出 3 } }3. Python# Python 程序通过枚举所有可能的子串统计字符串中长度大于等于 2 的回文子串数量 # 函数判断子串 s[i..j] 是否为回文 def isPalindrome(s, i, j): while i j: if s[i] ! s[j]: return False i 1 j - 1 return True def countPS(s): n len(s) # 枚举所有长度大于 1 的子串 res 0 for i in range(n): for j in range(i 1, n): # 如果从 i 到 j 的子串是回文结果加 1 if isPalindrome(s, i, j): res 1 return res if __name__ __main__: s abaab print(countPS(s))4. C#// C# 程序通过枚举所有可能的子串统计字符串中长度 2 的回文子串数量 using System; class DSA { // 函数判断子串 s[i..j] 是否为回文 static bool isPalindrome(string s, int i, int j) { while (i j) { if (s[i] ! s[j]) return false; i; j--; } return true; } static int countPS(string s) { int n s.Length; // 枚举所有长度大于 1 的子串 int res 0; for (int i 0; i n; i) { for (int j i 1; j n; j) { // 如果从 i 到 j 的子串是回文结果加 1 if (isPalindrome(s, i, j)) res; } } return res; } static void Main() { string s abaab; Console.WriteLine(countPS(s)); // 输出 3 } }5. JavaScript// JavaScript 程序通过枚举所有可能的子串统计字符串中长度大于等于 2 的回文子串总数 function isPalindrome(s, i, j) { while (i j) { if (s[i] ! s[j]) return false; i; j--; } return true; } function countPS(s) { let n s.length; // 枚举所有长度大于 1 的子串 let res 0; for (let i 0; i n; i) { for (let j i 1; j n; j) { // 如果从 i 到 j 的子串是回文结果加 1 if (isPalindrome(s, i, j)) res; } } return res; } // 测试代码 let s abaab; console.log(countPS(s));(三)代码输出和算法复杂度输出3时间复杂度O(n³)空间复杂度O(1)三、【优化解法-1】使用记忆化搜索 —— 时间复杂度O(n²)空间复杂度O(n²)(一) 解法思路仔细观察可以发现该递归解法具备动态规划的两大核心性质最优子结构判断子串是否为回文的问题isPalindrome(i, j)依赖于子问题isPalindrome(i 1, j - 1)的最优解。通过求解规模更小的子结构即可高效判断完整子串是否为回文。重复子问题算法会多次重复计算相同的子问题。例如isPalindrome(i 2, j - 2)既会在求解isPalindrome(i, j)时被计算也会在求解isPalindrome(i 1, j - 1)时重复运算这类冗余计算就构成了重复子问题。递归解法中仅有两个变化参数 i 和 j取值范围均为 0∼n。因此我们可以创建一个大小为 n×n 的二维数组用于记忆化存储。将该数组初始化为 −1代表初始状态下所有子问题均未计算。每次运算前先检查记忆化数组仅当值为 −1 时才执行递归调用。若区间 [i,j] 的子串是回文则记录memo[i][j] 1否则记录为0。(二) 使用 5 种语言实现1. C// C 程序使用记忆化搜索统计字符串中所有回文子串数量 // 仅统计长度 2 的回文子串 #include iostream #include vector #include string using namespace std; // 记忆化递归函数判断子串 s[i..j] 是否为回文 int isPalindrome(int i, int j, string s, vectorvectorint memo) { // 长度为 1 的子串一定是回文 if (i j) return 1; // 长度为 2 的子串两个字符相同则是回文 if (j i 1 s[i] s[j]) return 1; // 如果当前子串已经计算过直接返回结果 if (memo[i][j] ! -1) return memo[i][j]; // 若两端字符相等且中间子串是回文则整体是回文 memo[i][j] (s[i] s[j] isPalindrome(i 1, j - 1, s, memo)); return memo[i][j]; } // 统计长度 2 的回文子串总数 int countPS(string s) { int n s.length(); // 记忆化表格初始化为 -1表示未计算 vectorvectorint memo(n, vectorint(n, -1)); int res 0; // 枚举所有长度 2 的子串 for (int i 0; i n; i) { for (int j i 1; j n; j) { // 如果是回文计数加 1 if (isPalindrome(i, j, s, memo)) { res; } } } return res; } // 主函数 int main() { string s abaab; cout countPS(s); // 输出 3 return 0; }2. Java// Java 程序使用记忆化搜索统计字符串中所有回文子串数量 // 仅统计长度 2 的回文子串 import java.util.Arrays; class DSA { static int isPalindrome(int i, int j, String s, int[][] memo) { // 长度为 1 的子串一定是回文 if (i j) return 1; // 长度为 2 的子串两个字符相同则是回文 if (j i 1 s.charAt(i) s.charAt(j)) return 1; // 如果当前子串已经计算过直接返回结果 if (memo[i][j] ! -1) return memo[i][j]; // 若两端字符相等且中间子串是回文则整体是回文 if(s.charAt(i) s.charAt(j) isPalindrome(i 1, j - 1, s, memo) 1) memo[i][j] 1; else memo[i][j] 0; return memo[i][j]; } static int countPS(String s) { int n s.length(); // 记忆化表格初始化为 -1表示未计算 int[][] memo new int[n][n]; for (int[] row : memo) { Arrays.fill(row, -1); } int res 0; // 枚举所有长度 2 的子串 for (int i 0; i n; i) { for (int j i 1; j n; j) { // 如果是回文计数加 1 if (isPalindrome(i, j, s, memo) 1) { res; } } } return res; } public static void main(String[] args) { String s abaab; System.out.println(countPS(s)); } }3. Python# Python 程序使用记忆化搜索统计给定字符串中所有回文子串的数量 # 仅统计长度 2 的回文子串 def isPalindrome(i, j, s, memo): # 长度为 1 的子串一定是回文 if i j: return 1 # 长度为 2 的子串若两个字符相同则是回文 if j i 1 and s[i] s[j]: return 1 # 如果当前子串已经计算过直接返回结果 if memo[i][j] ! -1: return memo[i][j] # 若两端字符相等且中间子串是回文则整体是回文 if s[i] s[j] and isPalindrome(i 1, j - 1, s, memo) 1: memo[i][j] 1 else: memo[i][j] 0 return memo[i][j] def countPS(s): n len(s) # 记忆化表格初始化为 -1表示未计算 memo [[-1 for i in range(n)] for i in range(n)] res 0 # 枚举所有长度 2 的子串 for i in range(n): for j in range(i 1, n): # 如果是回文计数加 1 if isPalindrome(i, j, s, memo) 1: res 1 return res if __name__ __main__: s abaab print(countPS(s))4. C#// C# 程序使用记忆化搜索统计字符串中所有回文子串数量 // 仅统计长度 2 的回文子串 using System; class DSA { static int IsPalindrome(int i, int j, string s, int[,] memo) { // 长度为 1 的子串一定是回文 if (i j) return 1; // 长度为 2 的子串两个字符相同则是回文 if (j i 1 s[i] s[j]) return 1; // 如果当前子串已计算过直接返回结果 if (memo[i, j] ! -1) return memo[i, j]; // 若两端字符相等且中间子串是回文则整体是回文 if (s[i] s[j] IsPalindrome(i 1, j - 1, s, memo) 1) { memo[i, j] 1; } else { memo[i, j] 0; } return memo[i, j]; } static int CountPS(string s) { int n s.Length; // 记忆化表格初始化为 -1表示未计算 int[,] memo new int[n, n]; for (int i 0; i n; i) { for (int j 0; j n; j) { memo[i, j] -1; } } int res 0; // 枚举所有长度 2 的子串 for (int i 0; i n; i) { for (int j i 1; j n; j) { // 如果是回文计数加 1 if (IsPalindrome(i, j, s, memo) 1) { res; } } } return res; } static void Main() { string s abaab; Console.WriteLine(CountPS(s)); } }5. JavaScript// JavaScript 程序使用记忆化搜索统计字符串中所有回文子串数量 // 仅统计长度 2 的回文子串 function isPalindrome(i, j, s, memo) { // 长度为 1 的子串一定是回文 if (i j) return 1; // 长度为 2 的子串两个字符相同则是回文 if (j i 1 s[i] s[j]) return 1; // 如果当前子串已经计算过直接返回结果 if (memo[i][j] ! -1) return memo[i][j]; // 若两端字符相等且中间子串是回文则整体是回文 if (s[i] s[j] isPalindrome(i 1, j - 1, s, memo) 1) memo[i][j] 1; else memo[i][j] 0; return memo[i][j]; } function countPS(s) { const n s.length; // 记忆化表格初始化为 -1表示未计算 const memo Array.from({ length: n }, () Array(n).fill(-1)); let res 0; // 枚举所有长度 2 的子串 for (let i 0; i n; i) { for (let j i 1; j n; j) { // 如果是回文计数加 1 if (isPalindrome(i, j, s, memo) 1) { res; } } } return res; } // 测试代码 const s abaab; console.log(countPS(s));(三)代码输出和算法复杂度输出3时间复杂度O(n²)空间复杂度O(n²)四、【优化解法-2】使用自底向上动态规划表格法— 时间复杂度O(n²)空间复杂度O(n²)(一) 解法思路我们创建一个大小为 n×n 的 dp 数组。但不能简单地从 i0 到 n-1、j 从 i 到 n-1 填充 dp 表。因为计算 (i, j) 的值时需要先知道 (i1, j-1) 的值。与矩阵链乘法类似我们需要借助间隔gap变量按对角线方向填充表格。基本情况 单个字符一定是回文即dp[i][i] true。 两个字符的子串若两个字符相同则是回文即当s[i] s[i1]时dp[i][i1] true。任意子串 s [i...j] 是回文的条件 子串的第一个字符和最后一个字符相同 去掉首尾字符后的剩余子串是回文即dp[i1][j-1] true。(二) 使用 5 种语言实现1. C// C 程序使用自底向上动态规划表格法统计字符串中长度 2 的回文子串数量 #include iostream #include vector #include string using namespace std; int countPS(string s) { int n s.length(); int res 0; // 记录回文子串总数 // 创建 dp 表dp[i][j] 表示子串 s[i..j] 是否是回文 vectorvectorbool dp(n, vectorbool(n, false)); // 长度为 1 的子串一定是回文不计入结果 for (int i 0; i n; i) { dp[i][i] true; } // 长度为 2 的子串两个字符相同则是回文计数 1 for (int i 0; i n - 1; i) { if (s[i] s[i 1]) { dp[i][i 1] true; res; } } // 处理长度 3 的回文子串gap 表示子串长度 - 1 for (int gap 2; gap n; gap) { for (int i 0; i n - gap; i) { int j i gap; // 子串结束位置 // 如果首尾字符相同且中间子串是回文则整体是回文 if (s[i] s[j] dp[i 1][j - 1]) { dp[i][j] true; res; } } } return res; } // 主函数 int main() { string s abaab; cout countPS(s) endl; // 输出 3 return 0; }2. Java// Java 程序使用自底向上动态规划表格法统计字符串中长度 2 的回文子串数量 import java.util.*; class DSA { static int countPS(String s) { int n s.length(); int res 0; // dp[i][j] 表示子串 s[i..j] 是否为回文 boolean[][] dp new boolean[n][n]; // 长度为 1 的子串一定是回文不统计 for (int i 0; i n; i) { dp[i][i] true; } // 长度为 2 的子串两个字符相同则是回文计数 1 for (int i 0; i n - 1; i) { if (s.charAt(i) s.charAt(i 1)) { dp[i][i 1] true; res; } } // 处理长度大于 2 的回文子串 for (int gap 2; gap n; gap) { for (int i 0; i n - gap; i) { int j i gap; // 首尾字符相等且中间子串是回文 → 整体是回文 if (s.charAt(i) s.charAt(j) dp[i 1][j - 1]) { dp[i][j] true; res; } } } return res; } public static void main(String[] args) { String s abaab; System.out.println(countPS(s)); } }3. Python# Python 程序使用自底向上动态规划表格法统计字符串中长度 2 的回文子串数量 def countPS(s): n len(s) res 0 # dp[i][j] 表示子串 s[i..j] 是否为回文 dp [[False] * n for i in range(n)] # 长度为 1 的子串一定是回文不统计 for i in range(n): dp[i][i] True # 长度为 2 的子串两个字符相同则是回文计数 1 for i in range(n - 1): if s[i] s[i 1]: dp[i][i 1] True res 1 # 处理长度大于 2 的回文子串 for gap in range(2, n): for i in range(n - gap): j i gap # 首尾字符相等且中间子串是回文 → 整体是回文 if s[i] s[j] and dp[i 1][j - 1]: dp[i][j] True res 1 return res if __name__ __main__: s abaab print(countPS(s))4. C#// C# 程序使用自底向上动态规划表格法统计字符串中长度 2 的回文子串数量 using System; class DSA { static int countPS(string s) { int n s.Length; int res 0; // dp[i,j] 表示子串 s[i..j] 是否为回文 bool[,] dp new bool[n, n]; // 长度为 1 的子串一定是回文不统计 for (int i 0; i n; i) { dp[i, i] true; } // 长度为 2 的子串两个字符相同则是回文计数 1 for (int i 0; i n - 1; i) { if (s[i] s[i 1]) { dp[i, i 1] true; res; } } // 处理长度大于 2 的回文子串 for (int gap 2; gap n; gap) { for (int i 0; i n - gap; i) { int j i gap; // 首尾字符相等且中间子串是回文 → 整体是回文 if (s[i] s[j] dp[i 1, j - 1]) { dp[i, j] true; res; } } } return res; } static void Main() { string s abaab; Console.WriteLine(countPS(s)); } }5. JavaScript// JavaScript 程序使用自底向上动态规划表格法统计字符串中长度 2 的回文子串数量 function countPS(s) { const n s.length; let res 0; // dp[i][j] 表示子串 s[i..j] 是否为回文 const dp Array.from({ length: n }, () Array(n).fill(false)); // 长度为 1 的子串一定是回文不统计 for (let i 0; i n; i) { dp[i][i] true; } // 长度为 2 的子串两个字符相同则是回文计数 1 for (let i 0; i n - 1; i) { if (s[i] s[i 1]) { dp[i][i 1] true; res; } } // 处理长度大于 2 的回文子串 for (let gap 2; gap n; gap) { for (let i 0; i n - gap; i) { const j i gap; // 首尾字符相等且中间子串是回文 → 整体是回文 if (s[i] s[j] dp[i 1][j - 1]) { dp[i][j] true; res; } } } return res; } // 测试代码 const s abaab; console.log(countPS(s));(三)代码输出和算法复杂度输出3时间复杂度O(n²)空间复杂度O(n²)五、【最优解法】Manacher马拉车 算法 —— 时间复杂度 O (n)空间复杂度 O (n)(一) 解法思路我们使用马拉车算法Manacher’s Algorithm通过在插入分隔符改造后的字符串中计算以每个字符为中心的回文最大半径在线性时间内找出所有回文子串。对于每个中心回文子串的数量与半径的一半成正比。将所有中心的结果求和后减去长度为 1 的回文子串即可只统计长度 ≥ 2 的回文子串。实现步骤① 预处理字符串在字符之间插入分隔符#并在首尾加入哨兵字符开头、结尾$避免越界判断。示例abba→#a#b#b#a#$② 初始化变量p[i]存储以位置i为中心的最长回文半径left, right记录当前最长回文的左右边界③ 遍历改造后的字符串对每个索引i执行找到i的对称点mirror left (right - i)如果i在当前回文窗口内i right初始化p[i] min(p[mirror], right - i)尝试以i为中心向两侧扩展回文如果扩展超出right更新边界left i - p[i]right i p[i]④ 统计回文子串总数对每个p[i]以i为中心的回文子串数量 ceil(p[i] / 2)全部累加得到总回文子串数⑤ 排除长度为 1 的回文长度为 1 的回文数量 原字符串长度n最终结果 总数 -n只保留长度 ≥ 2 的回文(二) 使用 5 种语言实现1. C#include iostream #include vector #include string using namespace std; // Manacher 算法类线性时间求所有回文子串 class manacher { public: // p[i]存储改造字符串中以 i 为中心的最长回文半径 vectorint p; // ms插入分隔符 # 和哨兵 $ 后的改造字符串 string ms; // 构造函数预处理字符串 执行 Manacher 算法 manacher(string s) { // 开头加哨兵 ms ; // 原字符之间插入 # for (char c : s) { ms #; ms c; } // 结尾加 # 和哨兵 $ ms #$; runManacher(); } // Manacher 算法核心计算回文半径数组 p void runManacher() { int n ms.size(); // 初始化半径数组为 0 p.assign(n, 0); // 当前最长回文的左右边界 l, r int l 0; int r 0; // 遍历改造后的字符串跳过首尾哨兵 for (int i 1; i n - 1; i) { // 求 i 关于中心 (l,r) 的对称点 int mirror r l - i; // 如果 i 在当前回文内部利用对称性初始化半径 p[i] max(0, min(r - i, p[mirror])); // 尝试向两侧扩展回文 while (ms[i 1 p[i]] ms[i - 1 - p[i]]) { p[i]; } // 如果扩展超出右边界更新边界 if (i p[i] r) { l i - p[i]; r i p[i]; } } } // 获取原字符串中以 cen 为中心的最长回文长度 int getLongest(int cen, int odd) { int pos 2 * cen 2 !odd; return p[pos]; } // 检查原字符串 s[l...r] 是否是回文 bool check(int l, int r) { int len r - l 1; int center (r l) / 2; int isOdd len % 2; return len getLongest(center, isOdd); } }; // 统计原字符串中 长度 2 的回文子串数量 int countPS(string s) { manacher m(s); int total 0; // 累加所有中心的回文子串数量 for (int i 0; i m.p.size(); i) { // 每个中心贡献 ceil(p[i]/2) 个回文子串 total (m.p[i] 1) / 2; } // 减去长度为 1 的回文只保留 2 的 return total - s.length(); } // 主函数 int main() { string s abbaeae; cout countPS(s); // 输出回文子串数量 return 0; }2. Javaimport java.util.ArrayList; import java.util.Collections; // Manacher 算法实现类 class Manacher { // p[i]存储改造字符串中以 i 为中心的最长回文半径 ArrayListInteger p; // 插入分隔符 # 和首尾哨兵字符 $ 后的改造字符串 String ms; // 构造函数预处理字符串并执行 Manacher 算法 Manacher(String s) { StringBuilder sb new StringBuilder(); sb.append(); // 首部哨兵防止越界 // 在每个字符前后添加 # for (char c : s.toCharArray()) { sb.append(#); sb.append(c); } sb.append(#$); // 尾部 # 和哨兵 $ ms sb.toString(); runManacher(); // 执行核心算法 } // Manacher 算法核心计算回文半径数组 p void runManacher() { int n ms.length(); p new ArrayList(Collections.nCopies(n, 0)); int l 0; // 当前最长回文的左边界 int r 0; // 当前最长回文的右边界 for (int i 1; i n - 1; i) { int mirror r l - i; // i 关于中心 (l, r) 的对称点 // 如果 i 在当前最长回文内部利用对称性初始化半径 if (i r) { p.set(i, Math.min(r - i, p.get(mirror))); } // 尝试以 i 为中心向两侧扩展回文 while (ms.charAt(i 1 p.get(i)) ms.charAt(i - 1 - p.get(i))) { p.set(i, p.get(i) 1); } // 如果扩展超出右边界更新最长回文的边界 if (i p.get(i) r) { l i - p.get(i); r i p.get(i); } } } // 获取原字符串中以 cen 为中心的最长回文长度 int getLongest(int cen, int odd) { int pos 2 * cen 2 (odd 0 ? 1 : 0); if (pos p.size()) { return 0; } return p.get(pos); } // 检查原字符串的子串 s[l...r] 是否为回文 boolean check(int l, int r) { int len r - l 1; int center (r l) / 2; int isOdd len % 2; return len getLongest(center, isOdd); } } class GfG { // 统计长度 2 的回文子串数量 public static int countPS(String s) { Manacher m new Manacher(s); int total 0; // 累加所有中心的回文子串数量 for (int i 0; i m.p.size(); i) { total (m.p.get(i) 1) / 2; } // 减去长度为 1 的回文只保留 2 的 return total - s.length(); } public static void main(String[] args) { String s abbaeae; System.out.println(countPS(s)); // 输出结果 } }3. Pythonclass Manacher: def __init__(self, s): # 插入分隔符 # 和首尾哨兵字符 、$ 后的改造字符串 self.ms for c in s: self.ms # c self.ms #$ # p[i]存储改造字符串中以 i 为中心的最长回文半径 self.p [0] * len(self.ms) # 执行核心算法 self.runManacher() # Manacher 算法核心计算回文半径数组 p def runManacher(self): n len(self.ms) l, r 0, 0 # 当前最长回文的左右边界 for i in range(1, n - 1): mirror r l - i # i 关于中心 (l, r) 的对称点 # 利用对称性初始化半径 self.p[i] max(0, min(r - i, self.p[mirror])) # 以 i 为中心向两侧扩展回文 while self.ms[i 1 self.p[i]] self.ms[i - 1 - self.p[i]]: self.p[i] 1 # 如果扩展超出右边界更新边界 if i self.p[i] r: l i - self.p[i] r i self.p[i] # 获取原字符串中以 cen 为中心的最长回文长度 def getLongest(self, cen, odd): pos 2 * cen 2 (0 if odd else 1) return self.p[pos] # 检查原字符串的子串 s[l...r] 是否为回文 def check(self, l, r): length r - l 1 center (r l) // 2 isOdd length % 2 return length self.getLongest(center, isOdd) # 统计长度 2 的回文子串数量 def countPS(s): m Manacher(s) total 0 for val in m.p: # 累加每个中心的所有回文子串数量向上取整除以 2 total (val 1) // 2 # 减去长度为 1 的回文只保留 2 的 return total - len(s) if __name__ __main__: s abbaeae print(countPS(s))4. C#using System; using System.Collections.Generic; class Manacher { // p[i]存储改造字符串中以 i 为中心的最长回文半径 public Listint p; // 插入分隔符 # 和哨兵 $ 后的改造字符串 public string ms; // 构造函数预处理字符串并执行 Manacher 算法 public Manacher(string s) { ms ; foreach (char c in s) { ms #; ms c; } ms #$; runManacher(); } // Manacher 算法核心计算回文半径数组 p void runManacher() { int n ms.Length; p new Listint(new int[n]); int l 0; int r 0; for (int i 1; i n - 1; i) { int mirror r l - i; // 如果 i 在当前回文内部利用对称点初始化半径 if (i r) { p[i] Math.Min(r - i, p[mirror]); } // 以 i 为中心向两侧扩展回文 while (ms[i 1 p[i]] ms[i - 1 - p[i]]) { p[i]; } // 更新最长回文的边界 if (i p[i] r) { l i - p[i]; r i p[i]; } } } // 获取原字符串中以 cen 为中心的最长回文长度 public int getLongest(int cen, int odd) { int pos 2 * cen 2 (odd 0 ? 1 : 0); if (pos p.Count) { return 0; } return p[pos]; } // 检查原字符串的子串 s[l...r] 是否是回文 public bool check(int l, int r) { int len r - l 1; int center (r l) / 2; int isOdd len % 2; return len getLongest(center, isOdd); } } class DSA { // 统计长度 2 的回文子串数量 public static int countPS(string s) { Manacher m new Manacher(s); int total 0; for (int i 0; i m.p.Count; i) { // 累加所有中心的回文子串数量 total (m.p[i] 1) / 2; } // 减去长度为 1 的回文 return total - s.Length; } static void Main(string[] args) { string s abbaeae; Console.WriteLine(countPS(s)); } }5. JavaScriptclass Manacher { // 构造函数构建改造后的字符串并执行 Manacher 算法 constructor(s) { // 插入分隔符 # 和首尾哨兵字符 、$避免越界 this.ms ; for (let c of s) { this.ms # c; } this.ms #$; // p[i] 存储以 i 为中心的最长回文半径 this.p new Array(this.ms.length).fill(0); this.runManacher(); } // Manacher 算法核心计算回文半径数组 runManacher() { const n this.ms.length; let l 0, r 0; // 当前最长回文的左右边界 for (let i 1; i n - 1; i) { let mirror r l - i; // 对称点 // 利用对称性初始化半径 if (i r mirror 0 mirror n) { this.p[i] Math.max(0, Math.min(r - i, this.p[mirror])); } // 以 i 为中心向两侧扩展回文 while (this.ms[i 1 this.p[i]] this.ms[i - 1 - this.p[i]]) { this.p[i]; } // 更新最长回文边界 if (i this.p[i] r) { l i - this.p[i]; r i this.p[i]; } } } // 获取原字符串中以 cen 为中心的最长回文长度 getLongest(cen, odd) { let pos 2 * cen 2 (odd ? 0 : 1); if (pos this.p.length) { return 0; } return this.p[pos]; } // 检查原字符串的子串 s[l...r] 是否为回文 check(l, r) { let len r - l 1; let center Math.floor((r l) / 2); let isOdd len % 2; return len this.getLongest(center, isOdd); } } // 统计长度 2 的回文子串总数 function countPS(s) { const m new Manacher(s); let total 0; for (let val of m.p) { total Math.floor((val 1) / 2); } // 减去长度为 1 的回文 return total - s.length; } // 测试代码 let s abbaeae; console.log(countPS(s));(三)代码输出和算法复杂度输出4时间复杂度O(n)空间复杂度O(n)

相关文章:

用100道题拿下你的算法面试(字符串篇-8):回文子串数目

一、面试问题 给定一个字符串 s,求出该字符串中长度大于或等于 2 的所有回文子串的总数量。若一个子串正读与反读完全相同,则该子串为回文子串。 示例 1: 输入:s "abaab" 输出:3 解释:长度…...

手把手教你用Verilog在Xilinx Spartan-6上驱动IS62LV256 SRAM:从时序图到状态机的完整避坑指南

基于Xilinx Spartan-6的SRAM控制器实战:从时序解析到状态机优化 在FPGA开发中,片外存储器的接口设计往往是工程师面临的第一个真正挑战。IS62LV256这类SRAM芯片虽然接口相对简单,但要将数据手册中的时序参数准确转化为可综合的Verilog代码&am…...

2025届毕业生推荐的六大降AI率网站推荐榜单

Ai论文网站排名(开题报告、文献综述、降aigc率、降重综合对比) TOP1. 千笔AI TOP2. aipasspaper TOP3. 清北论文 TOP4. 豆包 TOP5. kimi TOP6. deepseek 需从多维度着手来降低AIGC(人工智能生成内容)可测率,首先…...

Maestro框架:用YAML简化移动端UI自动化测试

1. 项目概述:从“RunMaestro/Maestro”看移动端UI自动化测试的演进如果你是一名移动端开发者或测试工程师,最近在GitHub上搜索自动化测试方案,大概率会看到一个名为“RunMaestro/Maestro”的项目热度飙升。这不仅仅是一个新的测试框架&#x…...

CREST分子构象搜索工具完整指南:从零开始掌握高效采样技术

CREST分子构象搜索工具完整指南:从零开始掌握高效采样技术 【免费下载链接】crest CREST - A program for the automated exploration of low-energy molecular chemical space. 项目地址: https://gitcode.com/gh_mirrors/crest/crest CREST(Con…...

机器学习损失函数:原理、选择与实战技巧

1. 机器学习中的损失函数:原理与实战解析在训练机器学习模型时,损失函数就像一位严格的教练,不断告诉模型"你现在的表现离完美还有多远"。作为从业十余年的算法工程师,我见过太多项目因为损失函数选择不当而导致效果不佳…...

VS Code + MCP + Cursor + Continue:多智能体开发工作流搭建(私有化部署+离线模型接入+权限沙箱实录)

更多请点击: https://intelliparadigm.com 第一章:VS Code MCP 插件生态概览与核心价值定位 MCP 是什么? MCP(Model Context Protocol)是由 OpenAI 提出的标准化协议,用于在 IDE 中安全、可扩展地集成大…...

【2026 VS Code MCP生态白皮书】:基于127家头部科技公司实测数据的插件选型决策矩阵

更多请点击: https://intelliparadigm.com 第一章:VS Code MCP生态演进与2026技术定位 VS Code 的 MCP(Model Control Plane)生态正从实验性插件架构迈向标准化智能代理协同平台。2024年发布的 VS Code 1.90 引入了 MCP Server 协…...

Docker AI Toolkit 2026正式发布:8个生产级AI插件一键下载,附官方签名验证与离线部署脚本

更多请点击: https://intelliparadigm.com 第一章:Docker AI Toolkit 2026正式发布与核心演进 Docker AI Toolkit 2026(简称 DAIT-2026)已于 2025 年 10 月 15 日正式 GA,标志着容器化 AI 开发进入“零配置智能编排”…...

为什么你的低代码应用在MCP 2026沙箱环境总报“ContextNotBound”错误?(附官方未公开的调试模式启用密钥)

更多请点击: https://intelliparadigm.com 第一章:ContextNotBound错误的本质与MCP 2026沙箱的上下文生命周期模型 错误根源解析 ContextNotBound 是 MCP 2026 沙箱运行时的核心异常之一,表明当前执行线程试图访问一个尚未被显式绑定&#…...

面试官亲述:一道“发红包”用例设计题,我凭什么给他通过?

上周帮部门做校招面试,最近面试了不少校招同学,简历都挺能打——自动化框架、接口测试、性能压测都写着,项目经历至少两三个。我问了一个问题:“如果让你测试微信发红包,你怎么设计测试用例?”7个人里面&am…...

C++程序的五大内存分区实例详解

C程序在运行时所占用的内存区域,一般可分为栈内存区、堆内存区、全局/静态内存区、文字常量内存区及程序代码区5大分区:下面使用日常开发中的编程实例,详细介绍一下这5个分区,以便大家能更深刻的理解这5大内存分区。1、栈内存区栈…...

C++程序简单示例

前言:很多小伙伴反应想要用C刷LeetCode,但是对于C语法不熟悉,对于很多算法和数据结构也不够了解。这就导致了刷题的时候需要四处查询资料,非常的麻烦。我们先来看一段C的示例代码:1234567// my first cpp file#include…...

C++ 常用关键字使用举例

1. static控制作用域、生命周期或类成员归属123456789101112131415// 1. 全局/命名空间:仅当前文件可见(避免跨文件重定义)static int global_static 10; // 其他文件无法通过 extern 访问// 2. 局部变量:生命周期延长至程序结束…...

告别“唯大厂论”:全球财富 500 强实体企业 IT 核心岗位的隐形红利

在当前的留学生家庭中,关于计算机科学(CS)与工程类专业的就业规划,往往笼罩着一种高度趋同的“名企焦虑”。许多家长和学生将目光死死锁定在硅谷的科技巨头或少数几家头部互联网大厂上。为了挤进这些竞争白热化的窄门,…...

RAPID-LLM:大模型分布式训练性能优化实践

1. RAPID-LLM:分布式LLM训练与推理的性能优化利器在当今AI领域,大语言模型(LLM)的训练与推理已成为技术前沿的热点。随着模型参数规模从十亿级向万亿级迈进,单卡GPU已无法满足计算和内存需求,分布式训练成为…...

Python在TVA算法架构优化中的创新应用(七)

前沿技术背景介绍:AI 智能体视觉系统(TVA,Transformer-based Vision Agent),是依托Transformer架构与因式智能体所构建的新一代视觉检测技术。它区别于传统机器视觉与早期AI视觉,代表了工业智能化转型与视觉…...

Python在TVA算法架构优化中的创新应用(六)

前沿技术背景介绍:AI 智能体视觉系统(TVA,Transformer-based Vision Agent),是依托Transformer架构与因式智能体所构建的新一代视觉检测技术。它区别于传统机器视觉与早期AI视觉,代表了工业智能化转型与视觉…...

AI日志分析系统:多代理自修正RAG架构解析与实践

1. 日志分析系统的现状与挑战现代软件系统产生的日志数据正以惊人的速度增长。根据2023年DevOps状态报告,大型互联网公司每天产生的日志量普遍超过1TB,而传统金融系统的日志量也达到了数百GB级别。这些日志包含了系统运行状态、错误信息、性能指标等关键…...

独享IP+动态IP结合核心逻辑,破解稳定与灵活的矛盾

在代理IP使用中,稳定与灵活往往难以兼顾:独享IP专属可用、纯净度高、稳定性强,适合长期业务,但灵活性不足,长期固定易被标记、封禁;动态IP切换灵活、IP资源充足,能规避封禁风险,但共…...

轮式与足式移动机器人的运动学/动力学约束与控制分析

轮式与足式移动机器人的运动学/动力学约束与控制分析 摘要 移动机器人按移动方式可大致分为轮式机器人、足式机器人与轮足混合式机器人三大类。轮式机器人在平坦地面上具有高速高效率的优势,但因非完整约束导致运动自由度受限;足式机器人能够通过离散落足…...

Cgo 中正确设置 C 结构体回调函数指针的完整方案

...

使用 Tonic 构建高性能异步 gRPC 服务

使用 Tonic 构建高性能异步 gRPC 服务 在分布式系统开发中,gRPC 作为 Google 开源的高性能 RPC 框架,凭借 Protobuf 二进制序列化的高效性和 HTTP/2 传输的优势,成为服务间通信的首选方案。而在 Rust 生态中,Tonic 框架以其原生异…...

06华夏之光永存・开源:黄大年茶思屋第20期全套解题战略总结

06华夏之光永存・开源:黄大年茶思屋第20期全套解题战略总结 一、摘要 本次黄大年茶思屋第20期5道核心技术难题,均直指鸿蒙全场景生态、端侧算力调度、跨端多媒体交互、智能家居感知、端侧系统优化等华为核心技术布局卡点。全套难题通过原约束过渡攻坚底层…...

05华夏之光永存・开源:黄大年茶思屋榜文解法「第20期 5题」 面向通用场景的泛屏幕视频重构技术

华夏之光永存・开源:黄大年茶思屋榜文解法「第20期 5题」 面向通用场景的泛屏幕视频重构技术 一、摘要 泛屏幕视频重构与跨屏适配领域,全球现代工程常规优化已触达绝对性能天花板,现有显著性检测硬切缩放、固定比例裁剪、单模态超分等方案、固…...

【2026年最新600套毕设项目分享】奶茶点餐小程序(30180)

有需要的同学,源代码和配套文档领取,加文章最下方的名片哦 一、项目演示 项目演示视频 项目演示视频2 项目演示视频3 二、资料介绍 完整源代码(前后端源代码SQL脚本)配套文档(LWPPT开题报告/任务书)远…...

CSS如何实现动态菜单导航栏_利用Flexbox与-hover交互

Flexbox导航栏需设display: flex和flex-wrap: nowrap;子项用flex: 1均分,或flex: 0 1 auto保自然宽;注意box-sizing、hover预占位、伪元素滑入、可访问性及IE11兼容写法。Flexbox布局让导航栏自动均分宽度用 display: flex 是最直接的解法&am…...

大模型的探索与实践-课程笔记(十一):大模型发展史与全球厂商业态全景

第一部分:从 NLP 到 Transformer 的底层架构演进早期的自然语言处理(NLP)主要依赖特征提取,大模型的基石是 Google 提出的架构革命。1. Transformer 与注意力机制 (2017年)起源:Google 2017年发表神作《Attention is a…...

AI分析报告参考:麦肯锡结构化分析核心使用原则

AI分析报告参考:麦肯锡结构化分析体系 目录 AI分析报告参考:麦肯锡结构化分析体系 一、底层唯一核心法则:MECE法则 麦肯锡原生定义 麦肯锡标准MECE拆解维度(5种通用合规维度) 正反案例(贴合你的工作场景) 反例(不符合MECE) 正例1(流程维度,严格符合MECE) 正例2(要…...

企业数仓揭秘:数据决策背后的核心引擎

公司里人人都在提的“数仓”,到底是什么? 目录 公司里人人都在提的“数仓”,到底是什么? 一、一句话讲透:数仓到底是什么? 二、关键区分:数仓 vs 业务数据库,90%的人都搞混了 三、为什么现在几乎所有公司,都必须建自己的数仓? 四、企业数仓的核心架构:分层设计,到…...