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

用100道题拿下你的算法面试(字符串篇-9):所有不同的(不重复)回文子串

一、面试问题给定一个由小写英文字母组成的字符串s找出该字符串中所有不重复的连续回文子串。示例 1输入字符串 s abaaa输出[ a, aa, aaa, aba, b ]解释以上列出了全部 5 个不重复的连续回文子串。示例 2输入字符串 s geek输出[ e, ee, g, k ]解释以上列出了全部 4 个不重复的连续回文子串。二、【朴素解法】生成所有子串 —— 时间复杂度O(n³ × log n)空间复杂度 O(n²)(一) 解法思路思路是生成所有可能的子串找出其中的回文子串并使用集合来存储所有不重复的结果。(二) 使用 5 种语言实现1. C#include iostream #include string #include vector #include set using namespace std; // 暴力解法找出字符串中所有不同的连续回文子串 // 时间复杂度 O(n³ log n) vectorstring palindromicSubstr(string s) { int n s.length(); // 用 set 自动去重存储所有不同的回文子串 setstring result; // 生成所有以 i 为起点的子串 for(int i 0; i n; i) { // 存储当前构造的子串 string cur ; // 子串结束位置 j for(int j i; j n; j) { cur s[j]; // 判断当前子串是否是回文 int l 0, r cur.length() - 1; bool isPalindrome true; while(l r) { if(cur[l] ! cur[r]) { isPalindrome false; break; } l; r--; } // 如果是回文插入 set 去重 if(isPalindrome) { result.insert(cur); } } } // 将 set 转为 vector 返回 vectorstring res(result.begin(), result.end()); return res; } // 主函数 int main() { string s abaaa; vectorstring result palindromicSubstr(s); // 输出结果 for(string s1 : result) cout s1 ; return 0; }2. Javaimport java.util.Set; import java.util.ArrayList; import java.util.TreeSet; public class DSA { // 暴力法返回字符串中所有不同的回文子串按字典序排序 public static ArrayListString palindromicSubstr(String s) { int n s.length(); // TreeSet自动去重 自动排序 SetString result new TreeSet(); // 生成所有子串 for (int i 0; i n; i) { // 存储当前构造的子串 String cur ; for (int j i; j n; j) { cur s.charAt(j); // 判断当前子串是否是回文 int l 0, r cur.length() - 1; boolean isPalindrome true; while (l r) { if (cur.charAt(l) ! cur.charAt(r)) { isPalindrome false; break; } l; r--; } // 如果是回文加入集合自动去重 if (isPalindrome) { result.add(cur); } } } // 把集合转成 ArrayList 返回 return new ArrayList(result); } public static void main(String[] args) { String s abaaa; ArrayListString result palindromicSubstr(s); for (String s1 : result) System.out.print(s1 ); } }3. Pythondef palindromicSubstr(s): n len(s) # 使用集合存储所有不重复的回文子串自动去重 result set() # 生成所有可能的子串 for i in range(n): # 存储当前正在构造的子串 cur for j in range(i, n): cur s[j] # 双指针法判断当前子串是否是回文 l, r 0, len(cur) - 1 is_palindrome True while l r: if cur[l] ! cur[r]: is_palindrome False break l 1 r - 1 # 如果是回文加入集合 if is_palindrome: result.add(cur) # 将集合转换为排序后的列表并返回 res sorted(result) return res if __name__ __main__: s abaaa result palindromicSubstr(s) for s1 in result: print(s1, end )4. C#using System; using System.Collections.Generic; class DSA { // 暴力解法查找所有不同的连续回文子串 public static Liststring palindromicSubstr(string s) { int n s.Length; // SortedSet自动去重 自动排序 SortedSetstring result new SortedSetstring(); // 生成所有子串 for (int i 0; i n; i) { // 存储当前构造的子串 string cur ; for (int j i; j n; j) { cur s[j]; // 双指针判断子串是否为回文 int l 0, r cur.Length - 1; bool isPalindrome true; while (l r) { if (cur[l] ! cur[r]) { isPalindrome false; break; } l; r--; } // 是回文就加入集合 if (isPalindrome) { result.Add(cur); } } } // 转换为 List 返回 return new Liststring(result); } static void Main() { string s abaaa; Liststring result palindromicSubstr(s); foreach (string s1 in result) Console.Write(s1 ); } }5. JavaScriptfunction palindromicSubstr(s) { const n s.length; // 使用 Set 存储所有不重复的回文子串自动去重 const result new Set(); // 生成所有可能的子串暴力枚举起点 i for (let i 0; i n; i) { // 存储当前正在构造的子串 let cur ; // 枚举子串终点 j for (let j i; j n; j) { cur s[j]; // 双指针法判断当前子串是否为回文 let l 0, r cur.length - 1; let isPalindrome true; while (l r) { if (cur[l] ! cur[r]) { isPalindrome false; break; } l; r--; } // 如果是回文加入集合 if (isPalindrome) { result.add(cur); } } } // 将集合转为数组并按字典序排序后返回 const res Array.from(result).sort(); return res; } // 测试代码 const s abaaa; const result palindromicSubstr(s); for (const s1 of result) { process.stdout.write(s1 ); }(三)代码输出和算法复杂度输出a aaa aba b aa时间复杂度O(n³ × log n)空间复杂度O(n²)三、【优化解法】使用Rabin-Karp滚动哈希 中心扩展法—— 时间复杂度 O (n²×log n)空间复杂度 O (n²)(一) 解法思路该解法的核心思路结合Rabin-Karp 双重哈希实现子串快速比对以此找出字符串中所有唯一的回文子串。以单个字符为中心处理奇数长度回文、以相邻字符对为中心处理偶数长度回文向两侧扩展并校验回文。每找到一个回文子串就计算其双重哈希值存入集合保证去重。同时借助二维标记数组记录回文所在位置。最终提取所有被标记的子串并返回。该方案不再直接存储字符串集合仅依靠整型哈希值完成比对大幅提升效率。(二) 使用 5 种语言实现1. C#include iostream #include string #include vector #include set using namespace std; // Rabin-Karp 双重哈希类用于快速计算子串哈希值 class RabinKarpHash { private: const int mod1 1e9 7; // 第一个大模数 const int mod2 1e9 9; // 第二个大模数 const int base1 31; // 第一个基数 const int base2 37; // 第二个基数 vectorint hash1, hash2; // 前缀哈希数组 vectorint power1, power2; // 基数幂次数组 // 模加法 int add(int a, int b, int mod) { a b; if (a mod) a - mod; return a; } // 模减法 int sub(int a, int b, int mod) { a - b; if (a 0) a mod; return a; } // 模乘法 int mul(int a, int b, int mod) { return (int)((1LL * a * b) % mod); } // 字符转数字a1, b2... int charToInt(char c) { return c - a 1; } public: // 构造函数预处理前缀哈希和幂次 RabinKarpHash(string s) { int n s.size(); hash1.resize(n); hash2.resize(n); power1.resize(n); power2.resize(n); hash1[0] charToInt(s[0]); hash2[0] charToInt(s[0]); power1[0] 1; power2[0] 1; for (int i 1; i n; i) { hash1[i] add(mul(hash1[i - 1], base1, mod1), charToInt(s[i]), mod1); power1[i] mul(power1[i - 1], base1, mod1); hash2[i] add(mul(hash2[i - 1], base2, mod2), charToInt(s[i]), mod2); power2[i] mul(power2[i - 1], base2, mod2); } } // 获取子串 s[l...r] 的双重哈希值 vectorint getSubHash(int l, int r) { int h1 hash1[r]; int h2 hash2[r]; if (l 0) { h1 sub(h1, mul(hash1[l - 1], power1[r - l 1], mod1), mod1); h2 sub(h2, mul(hash2[l - 1], power2[r - l 1], mod2), mod2); } return {h1, h2}; } }; // 主函数返回所有不同的回文子串 vectorstring palindromicSubstr(string s) { RabinKarpHash rb(s); int n s.length(); setvectorint disPalin; // 存储哈希值用于去重 vectorvectorbool mark(n, vectorbool(n, false)); // 标记回文位置 // 中心扩展奇数长度回文 for (int i 0; i n; i) { int left i, right i; while (left 0 right n s[left] s[right]) { vectorint hashVal rb.getSubHash(left, right); if (disPalin.find(hashVal) disPalin.end()) { disPalin.insert(hashVal); mark[left][right] true; } left--; right; } } // 中心扩展偶数长度回文 for (int i 0; i n - 1; i) { int left i, right i 1; while (left 0 right n s[left] s[right]) { vectorint hashVal rb.getSubHash(left, right); if (disPalin.find(hashVal) disPalin.end()) { disPalin.insert(hashVal); mark[left][right] true; } left--; right; } } // 根据标记数组收集所有回文子串 vectorstring res; for (int i 0; i n; i) { string sub ; for (int j i; j n; j) { sub.push_back(s[j]); if (mark[i][j] true) { res.push_back(sub); } } } return res; } // 主程序 int main() { string s abaaa; vectorstring result palindromicSubstr(s); for (string str : result) cout str ; return 0; }2. Javaimport java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; // Rabin-Karp 双重哈希类快速计算子串哈希值用于去重 class RabinKarpHash { private final int mod1 (int)1e9 7; // 模数1 private final int mod2 (int)1e9 9; // 模数2 private final int base1 31; // 基数1 private final int base2 37; // 基数2 private int[] hash1, hash2; // 前缀哈希数组 private int[] power1, power2; // 幂次数组 // 模加法 int add(int a, int b, int mod) { a b; if (a mod) a - mod; return a; } // 模减法 int sub(int a, int b, int mod) { a - b; if (a 0) a mod; return a; } // 模乘法 int mul(int a, int b, int mod) { return (int)(((long)a * b) % mod); } // 字符转数字 a-1, b-2... int charToInt(char c) { return c - a 1; } // 构造函数预处理哈希与幂次 public RabinKarpHash(String s) { int n s.length(); hash1 new int[n]; hash2 new int[n]; power1 new int[n]; power2 new int[n]; hash1[0] charToInt(s.charAt(0)); hash2[0] charToInt(s.charAt(0)); power1[0] 1; power2[0] 1; for (int i 1; i n; i) { hash1[i] add(mul(hash1[i - 1], base1, mod1), charToInt(s.charAt(i)), mod1); power1[i] mul(power1[i - 1], base1, mod1); hash2[i] add(mul(hash2[i - 1], base2, mod2), charToInt(s.charAt(i)), mod2); power2[i] mul(power2[i - 1], base2, mod2); } } // 获取子串 s[l...r] 的双重哈希 public ListInteger getSubHash(int l, int r) { int h1 hash1[r]; int h2 hash2[r]; if (l 0) { h1 sub(h1, mul(hash1[l - 1], power1[r - l 1], mod1), mod1); h2 sub(h2, mul(hash2[l - 1], power2[r - l 1], mod2), mod2); } return Arrays.asList(h1, h2); } } class DSA { // 主函数返回所有不同的回文子串 public static ArrayListString palindromicSubstr(String s) { RabinKarpHash rb new RabinKarpHash(s); int n s.length(); SetListInteger disPalin new HashSet(); // 存储哈希值去重 boolean[][] mark new boolean[n][n]; // 标记回文位置 // 中心扩展奇数长度回文 for (int i 0; i n; i) { int left i, right i; while (left 0 right n s.charAt(left) s.charAt(right)) { ListInteger hashVal rb.getSubHash(left, right); if (!disPalin.contains(hashVal)) { disPalin.add(hashVal); mark[left][right] true; } left--; right; } } // 中心扩展偶数长度回文 for (int i 0; i n - 1; i) { int left i, right i 1; while (left 0 right n s.charAt(left) s.charAt(right)) { ListInteger hashVal rb.getSubHash(left, right); if (!disPalin.contains(hashVal)) { disPalin.add(hashVal); mark[left][right] true; } left--; right; } } // 根据标记收集所有回文子串 ArrayListString res new ArrayList(); for (int i 0; i n; i) { StringBuilder sub new StringBuilder(); for (int j i; j n; j) { sub.append(s.charAt(j)); if (mark[i][j]) { res.add(sub.toString()); } } } return res; } public static void main(String[] args) { String s abaaa; ArrayListString result palindromicSubstr(s); for (String str : result) { System.out.print(str ); } } }3. Python# Rabin-Karp 双重哈希类用于快速计算子串哈希值实现高效去重 class RabinKarpHash: def __init__(self, s): self.mod1 10**9 7 # 第一个大模数 self.mod2 10**9 9 # 第二个大模数 self.base1 31 # 第一个基数 self.base2 37 # 第二个基数 n len(s) self.hash1 [0] * n # 第一组前缀哈希 self.hash2 [0] * n # 第二组前缀哈希 self.power1 [0] * n # 第一组基数幂次 self.power2 [0] * n # 第二组基数幂次 self.hash1[0] self.charToInt(s[0]) self.hash2[0] self.charToInt(s[0]) self.power1[0] 1 self.power2[0] 1 # 预处理前缀哈希和幂次数组 for i in range(1, n): self.hash1[i] self.add(self.mul(self.hash1[i-1], self.base1, self.mod1), self.charToInt(s[i]), self.mod1) self.power1[i] self.mul(self.power1[i-1], self.base1, self.mod1) self.hash2[i] self.add(self.mul(self.hash2[i-1], self.base2, self.mod2), self.charToInt(s[i]), self.mod2) self.power2[i] self.mul(self.power2[i-1], self.base2, self.mod2) # 模加法 def add(self, a, b, mod): a b if a mod: a - mod return a # 模减法 def sub(self, a, b, mod): a - b if a 0: a mod return a # 模乘法 def mul(self, a, b, mod): return (a * b) % mod # 字符转数字a1, b2... def charToInt(self, c): return ord(c) - ord(a) 1 # 获取子串 s[l...r] 的双重哈希值用于去重 def getSubHash(self, l, r): h1 self.hash1[r] h2 self.hash2[r] if l 0: h1 self.sub(h1, self.mul(self.hash1[l-1], self.power1[r-l1], self.mod1), self.mod1) h2 self.sub(h2, self.mul(self.hash2[l-1], self.power2[r-l1], self.mod2), self.mod2) return (h1, h2) # 主函数返回字符串中所有不同的连续回文子串 def palindromicSubstr(s): rb RabinKarpHash(s) n len(s) disPalin set() # 存储哈希值自动去重 mark [[False] * n for _ in range(n)] # 标记回文位置 # 中心扩展奇数长度回文 for i in range(n): left i right i while left 0 and right n and s[left] s[right]: hash_val rb.getSubHash(left, right) if hash_val not in disPalin: disPalin.add(hash_val) mark[left][right] True left - 1 right 1 # 中心扩展偶数长度回文 for i in range(n - 1): left i right i 1 while left 0 and right n and s[left] s[right]: hash_val rb.getSubHash(left, right) if hash_val not in disPalin: disPalin.add(hash_val) mark[left][right] True left - 1 right 1 # 根据标记数组收集所有回文子串 res [] for i in range(n): sub for j in range(i, n): sub s[j] if mark[i][j]: res.append(sub) return res # 测试主程序 if __name__ __main__: s abaaa result palindromicSubstr(s) print( .join(result))4. C#using System; using System.Collections.Generic; // Rabin-Karp 双重哈希类用于快速计算子串哈希值实现高效去重 class RabinKarpHash { private readonly int mod1 1000000007; // 模数1 private readonly int mod2 1000000009; // 模数2 private readonly int base1 31; // 基数1 private readonly int base2 37; // 基数2 private Listint hash1, hash2; // 前缀哈希数组 private Listint power1, power2; // 幂次数组 // 模加法 private int add(int a, int b, int mod) { a b; if (a mod) a - mod; return a; } // 模减法 private int sub(int a, int b, int mod) { a - b; if (a 0) a mod; return a; } // 模乘法 private int mul(int a, int b, int mod) { return (int)(((long)a * b) % mod); } // 字符转数字 a-1, b-2... private int charToInt(char c) { return c - a 1; } // 构造函数预处理前缀哈希和幂次 public RabinKarpHash(string s) { int n s.Length; hash1 new Listint(new int[n]); hash2 new Listint(new int[n]); power1 new Listint(new int[n]); power2 new Listint(new int[n]); hash1[0] charToInt(s[0]); hash2[0] charToInt(s[0]); power1[0] 1; power2[0] 1; for (int i 1; i n; i) { hash1[i] add(mul(hash1[i - 1], base1, mod1), charToInt(s[i]), mod1); power1[i] mul(power1[i - 1], base1, mod1); hash2[i] add(mul(hash2[i - 1], base2, mod2), charToInt(s[i]), mod2); power2[i] mul(power2[i - 1], base2, mod2); } } // 获取子串 s[l...r] 的双重哈希 public Tupleint, int getSubHash(int l, int r) { int h1 hash1[r]; int h2 hash2[r]; if (l 0) { h1 sub(h1, mul(hash1[l - 1], power1[r - l 1], mod1), mod1); h2 sub(h2, mul(hash2[l - 1], power2[r - l 1], mod2), mod2); } return Tuple.Create(h1, h2); } } class DSA { // 主函数返回所有不同的连续回文子串 public static Liststring palindromicSubstr(string s) { RabinKarpHash rb new RabinKarpHash(s); int n s.Length; HashSetstring disPalinSet new HashSetstring(); // 存储哈希字符串用于去重 bool[,] mark new bool[n, n]; // 标记回文位置 // 中心扩展奇数长度回文 for (int i 0; i n; i) { int left i, right i; while (left 0 right n s[left] s[right]) { var hashleftright rb.getSubHash(left, right); string key hashleftright.Item1 # hashleftright.Item2; if (!disPalinSet.Contains(key)) { disPalinSet.Add(key); mark[left, right] true; } left--; right; } } // 中心扩展偶数长度回文 for (int i 0; i n - 1; i) { int left i, right i 1; while (left 0 right n s[left] s[right]) { var hashleftright rb.getSubHash(left, right); string key hashleftright.Item1 # hashleftright.Item2; if (!disPalinSet.Contains(key)) { disPalinSet.Add(key); mark[left, right] true; } left--; right; } } // 根据标记收集所有回文子串 Liststring res new Liststring(); for (int i 0; i n; i) { string sub ; for (int j i; j n; j) { sub s[j]; if (mark[i, j]) { res.Add(sub); } } } return res; } // 测试主函数 public static void Main() { string s abaaa; Liststring result palindromicSubstr(s); foreach (string str in result) { Console.Write(str ); } } }5. JavaScript// Rabin-Karp 双重哈希类快速计算子串哈希用于高效去重 function RabinKarpHash(s) { this.mod1 1e9 7; // 模数1 this.mod2 1e9 9; // 模数2 this.base1 31; // 基数1 this.base2 37; // 基数2 // 前缀哈希数组 幂次数组 this.hash1 new Array(s.length).fill(0); this.hash2 new Array(s.length).fill(0); this.power1 new Array(s.length).fill(0); this.power2 new Array(s.length).fill(0); // 字符转数字 a-1, b-2... const charToInt c c.charCodeAt(0) - a.charCodeAt(0) 1; // 初始化第一个字符 this.hash1[0] charToInt(s[0]); this.hash2[0] charToInt(s[0]); this.power1[0] 1; this.power2[0] 1; // 预处理前缀哈希和幂次 for (let i 1; i s.length; i) { this.hash1[i] this.add(this.mul(this.hash1[i - 1], this.base1, this.mod1), charToInt(s[i]), this.mod1); this.power1[i] this.mul(this.power1[i - 1], this.base1, this.mod1); this.hash2[i] this.add(this.mul(this.hash2[i - 1], this.base2, this.mod2), charToInt(s[i]), this.mod2); this.power2[i] this.mul(this.power2[i - 1], this.base2, this.mod2); } } // 模加法 RabinKarpHash.prototype.add function(a, b, mod) { a b; if (a mod) a - mod; return a; }; // 模减法 RabinKarpHash.prototype.sub function(a, b, mod) { a - b; if (a 0) a mod; return a; }; // 模乘法 RabinKarpHash.prototype.mul function(a, b, mod) { return ((a * b) % mod mod) % mod; }; // 获取子串 s[l...r] 的双重哈希 RabinKarpHash.prototype.getSubHash function(l, r) { let h1 this.hash1[r]; let h2 this.hash2[r]; if (l 0) { h1 this.sub(h1, this.mul(this.hash1[l - 1], this.power1[r - l 1], this.mod1), this.mod1); h2 this.sub(h2, this.mul(this.hash2[l - 1], this.power2[r - l 1], this.mod2), this.mod2); } return [h1, h2]; }; // 主函数返回所有不同的连续回文子串 function palindromicSubstr(s) { const n s.length; const mark Array.from({ length: n }, () Array(n).fill(false)); // 标记回文位置 const disPalinSet new Set(); // 存储哈希字符串用于去重 const rk new RabinKarpHash(s); // 中心扩展奇数长度回文 for (let i 0; i n; i) { let left i, right i; while (left 0 right n s[left] s[right]) { const [h1, h2] rk.getSubHash(left, right); const key ${h1}#${h2}; if (!disPalinSet.has(key)) { disPalinSet.add(key); mark[left][right] true; } left--; right; } } // 中心扩展偶数长度回文 for (let i 0; i n - 1; i) { let left i, right i 1; while (left 0 right n s[left] s[right]) { const [h1, h2] rk.getSubHash(left, right); const key ${h1}#${h2}; if (!disPalinSet.has(key)) { disPalinSet.add(key); mark[left][right] true; } left--; right; } } // 根据标记收集所有回文子串 const res []; for (let i 0; i n; i) { let sub ; for (let j i; j n; j) { sub s[j]; if (mark[i][j]) { res.push(sub); } } } return res; } // 测试主程序 const s abaaa; const result palindromicSubstr(s); console.log(result.join( ));(三)代码输出和算法复杂度输出a aba b aa aaa时间复杂度O (n² × log n)在最坏情况下字符串中可能存在O(n²)个回文子串。由于使用了平衡二叉搜索树结构的集合每次哈希值插入操作需要O(log n)时间因此总时间复杂度为O(n²×log n)。空间复杂度O (n²)我们使用了大小为O(n²)的二维标记数组同时集合最多可存储O(n²)个唯一的回文哈希值因此整体辅助空间复杂度为O(n²)。四、【最优解法】使用动态规划 KMP 算法—— 时间复杂度 O (n²)空间复杂度 O (n²)(一) 解法思路使用动态规划找出字符串中的所有回文子串再借助KMP 算法对结果进行去重最后输出所有不重复的回文子串及其数量。按照以下步骤实现第一步遍历所有可能的子串借助动态规划判断每个子串是否为回文。第二步从下标 0 开始遍历每个位置运用KMP 算法比对字符串的前缀与后缀。若某个子串既是回文且自身前缀与后缀完全匹配则对其进行标记例如将对应 DP 数组的值置为 false以此剔除重复的回文子串。第三步遍历全部子串输出 DP 数组中仍被标记为回文的子串此类有效子串的总个数即为不重复回文子串的总数。(二) 使用 5 种语言实现1. C#include iostream #include string #include vector using namespace std; // 最优解法动态规划 DP KMP 算法 // 找出所有不同的连续回文子串 vectorstring palindromicSubstr(string s) { int n s.length(); // DP 数组dp[i][j] 表示子串 s[i..j] 是否为回文 vectorvectorbool dp(n, vectorbool(n, false)); // 基础情况长度为 1 的子串一定是回文 for (int i 0; i n; i) { dp[i][i] 1; // 长度为 2 的子串两个字符相等就是回文 if (i n - 1 s[i] s[i 1]) { dp[i][i 1] 1; } } // 处理长度 3 的子串 for (int len 3; len n; len) { for (int i 0; i len - 1 n; i) { int j i len - 1; // 两端字符相等 且 中间子串是回文 if (s[i] s[j] dp[i 1][j - 1]) { dp[i][j] true; } } } // KMP 数组用于去重剔除重复的回文子串 vectorint kmp(n, 0); // 对每个起点 i 执行 KMP标记重复的回文 for (int i 0; i n; i) { int j 0, k 1; while (k i n) { if (s[j i] s[k i]) { // 核心标记重复回文设为 false dp[k i - j][k i] false; kmp[k] j; } else if (j 0) { j kmp[j - 1]; } else { kmp[k] 0; } } } // 收集所有未被标记的唯一的回文子串 vectorstring result; for (int i 0; i n; i) { string cur; for (int j i; j n; j) { cur s[j]; if (dp[i][j]) { result.push_back(cur); } } } return result; } // 主函数 int main() { string s abaaa; vectorstring result palindromicSubstr(s); for(string s : result) cout s ; return 0; }2. Javaimport java.util.ArrayList; import java.util.Arrays; class DSA { // 最优解法动态规划 DP KMP 算法 // 找出字符串中所有不同的连续回文子串 static ArrayListString palindromicSubstr(String s) { int n s.length(); // DP 二维数组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 的子串两个字符相等就是回文 if (i n - 1 s.charAt(i) s.charAt(i 1)) { dp[i][i 1] true; } } // 处理长度 3 的子串 for (int len 3; len n; len) { for (int i 0; i len - 1 n; i) { int j i len - 1; // 两端字符相等 且 中间子串是回文 if (s.charAt(i) s.charAt(j) dp[i 1][j - 1]) { dp[i][j] true; } } } // KMP 数组用于去重剔除重复的回文子串 int[] kmp new int[n]; Arrays.fill(kmp, 0); // 对每个起点 i 执行 KMP标记重复的回文为 false for (int i 0; i n; i) { int j 0, k 1; while (k i n) { if (s.charAt(j i) s.charAt(k i)) { // 核心标记重复回文设为 false dp[k i - j][k i] false; kmp[k] j; } else if (j 0) { j kmp[j - 1]; } else { kmp[k] 0; } } } // 收集所有未被标记的唯一的回文子串 ArrayListString result new ArrayList(); for (int i 0; i n; i) { String cur ; for (int j i; j n; j) { cur s.charAt(j); if (dp[i][j]) { result.add(cur); } } } return result; } // 主函数 public static void main(String[] args) { String s abaaa; ArrayListString result palindromicSubstr(s); for (String s1 : result) System.out.print(s1 ); } }3. Pythondef palindromicSubstr(s): n len(s) # DP 二维数组dp[i][j] 表示子串 s[i..j] 是否为回文 dp [[False for _ in range(n)] for _ in range(n)] # 基础情况长度为 1 的子串一定是回文 for i in range(n): dp[i][i] True # 长度为 2 的子串两个字符相等就是回文 if i n - 1 and s[i] s[i 1]: dp[i][i 1] True # 处理长度 3 的子串 for length in range(3, n 1): for i in range(n - length 1): j i length - 1 # 两端字符相等 且 中间子串是回文 if s[i] s[j] and dp[i 1][j - 1]: dp[i][j] True # KMP 数组用于去重剔除重复的回文子串 kmp [0] * n # 对每个起点 i 执行 KMP标记重复的回文为 false for i in range(n): j 0 k 1 while k i n: if s[i j] s[i k]: # 核心标记重复回文设为 false dp[i k - j][i k] False kmp[k] j 1 j 1 k 1 elif j 0: j kmp[j - 1] else: kmp[k] 0 k 1 # 收集所有未被标记的唯一的回文子串 result [] for i in range(n): cur for j in range(i, n): cur s[j] if dp[i][j]: result.append(cur) return result # 主函数 if __name__ __main__: s abaaa result palindromicSubstr(s) for s in result: print(s, end )4. C#using System; using System.Collections.Generic; class GfG { // 最优解法动态规划 DP KMP 算法 // 找出字符串中所有不同的连续回文子串 static Liststring palindromicSubstr(ref string s) { int n s.Length; // DP 二维数组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 的子串两个字符相等就是回文 if (i n - 1 s[i] s[i 1]) dp[i, i 1] true; } // 处理长度 3 的子串 for (int len 3; len n; len) { for (int i 0; i len - 1 n; i) { int j i len - 1; // 两端字符相等 且 中间子串是回文 if (s[i] s[j] dp[i 1, j - 1]) dp[i, j] true; } } // KMP 数组用于去重剔除重复的回文子串 int[] kmp new int[n]; for (int i 0; i n; i) { kmp[i] 0; } // 对每个起点 i 执行 KMP标记重复的回文为 false for (int i 0; i n; i) { int j 0, k 1; while (k i n) { if (s[i j] s[i k]) { // 核心标记重复回文设为 false dp[i k - j, i k] false; kmp[k] j; k; } else if (j 0) { j kmp[j - 1]; } else { kmp[k] 0; k; } } } // 收集所有未被标记的唯一的回文子串 Liststring result new Liststring(); for (int i 0; i n; i) { string cur ; for (int j i; j n; j) { cur s[j]; if (dp[i, j]) result.Add(cur); } } return result; } // 主函数 static void Main() { string s abaaa; Liststring result palindromicSubstr(ref s); foreach (string ss in result) Console.Write(ss ); } }5. JavaScriptfunction palindromicSubstr(s) { let n s.length; // DP 二维数组dp[i][j] 表示子串 s[i..j] 是否为回文 let dp new Array(n); for (let i 0; i n; i) { dp[i] new Array(n).fill(false); } // 基础情况长度为 1 的子串一定是回文 for (let i 0; i n; i) { dp[i][i] true; // 长度为 2 的子串两个字符相等就是回文 if (i n - 1 s[i] s[i 1]) dp[i][i 1] true; } // 处理长度 3 的子串 for (let len 3; len n; len) { for (let i 0; i len - 1 n; i) { let j i len - 1; // 两端字符相等 且 中间子串是回文 if (s[i] s[j] dp[i 1][j - 1]) dp[i][j] true; } } // KMP 数组用于去重剔除重复的回文子串 let kmp new Array(n).fill(0); // 对每个起点 i 执行 KMP标记重复的回文为 false for (let i 0; i n; i) { let j 0, k 1; while (k i n) { if (s[i j] s[i k]) { // 核心标记重复回文设为 false dp[i k - j][i k] false; kmp[k] j; k; } else if (j 0) { j kmp[j - 1]; } else { kmp[k] 0; k; } } } // 收集所有未被标记的唯一的回文子串 let result []; for (let i 0; i n; i) { let cur ; for (let j i; j n; j) { cur s[j]; if (dp[i][j]) result.push(cur); } } return result; } // 测试主函数 let s abaaa; let result palindromicSubstr(s); console.log(result.join( ));(三)代码输出和算法复杂度输出a aba b aa aaa时间复杂度O(n²)空间复杂度O(n²)

相关文章:

用100道题拿下你的算法面试(字符串篇-9):所有不同的(不重复)回文子串

一、面试问题给定一个由小写英文字母组成的字符串 s,找出该字符串中所有不重复的连续回文子串。示例 1:输入:字符串 s "abaaa"输出:[ "a", "aa", "aaa", "aba", "b"…...

用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(要…...