647. Palindromic Substrings

网友投稿 647 2022-09-04

647. Palindromic Substrings

647. 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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"Output: 6Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note: The input string length won’t exceed 1000.

O(n)的时间复杂度。 思路: 先对字符串进行改造(例如原字符串是”bab”,改造后是”#b#a#b#”),接着对改造后的字符串运行Manacher’s Algorithm(“马拉车”算法),得到以s[i]为中心的回文串的半径RL[i](不包括中心。例如”a”的半径就是0;”bab”以”a”为中心,半径就是1),显然,以s[i]为中心,RL[i]为半径的回文串中含有的字回文串数目是(RL[i] + 1) / 2个。最后只要将每个(RL[i] + 1) / 2加和就是结果。

class Solution { public int countSubstrings(String s) { String rs = "#"; for(int i = 0; i < s.length(); i++) rs = rs + s.charAt(i) + "#"; int[] RL = new int[rs.length()]; int pos = 0, maxRight = 0, count = 0; for(int i = 0; i < rs.length(); i++) { if(i < maxRight) { RL[i] = Math.min(maxRight - i, RL[2 * pos - i]); } while(i - RL[i] - 1 >= 0 && i + RL[i] + 1 < rs.length() && rs.charAt(i - RL[i] - 1) == rs.charAt(i + RL[i] + 1)) { RL[i]++; } if(i + RL[i] > maxRight) { pos = i; maxRight = i + RL[i]; } count += (RL[i] + 1)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:PHP 新特性:闭包和匿名函数,估计你用得很少(php文件用什么软件打开)
下一篇:659. Split Array into Consecutive Subsequences
相关文章

 发表评论

暂时没有评论,来抢沙发吧~