LeetCode-647. Palindromic Substrings

网友投稿 274 2022-08-29

LeetCode-647. Palindromic Substrings

​​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^2),空间复杂度O(1)解法。

class Solution {public: int countSubstrings(string s) { int n = s.length(), ans = 0; if (n < 2){ return n; } for (int i = 0; i < n; i++){ ans++; int j = i, k = i, l = i, m = i; while (s[j - 1] == s[k + 1]){ ans++; j--; k++; if (j < 1 || k > n - 2){ break; } } while (s[l] == s[m + 1]){ ans++; l--; m++; if (l < 0 || m > n - 2){ break; } } } return ans; }};

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

上一篇:LeetCode-947. Most Stones Removed with Same Row or Column
下一篇:没有执行,管理就是零!(没有执行管理就是零读后感)
相关文章

 发表评论

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