首页 > 代码库 > [leetcode-647-Palindromic Substrings]
[leetcode-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: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won‘t exceed 1000.
思路:
从字符串s中的位置s[i]出发,分别判断奇数长度和偶数长度的子字符串是否为回文串。
判断奇数长度: 将index指向同一个字符s[i],然后循环判断s[i-1]和s[i+1]是否相等。
判断偶数长度: 将index指向相邻两个字符s[i],s[i+1],然后循环判断s[i]和s[i+1]是否相等,,然后分别向左和向右移动字符指针。
void ifsub(string& s,int l,int r,int& cnt) { while (l >= 0 && r < s.length() && s[l] == s[r]) { cnt++; l--; r++; } } int countSubstrings(string s) { if (s.length() == 0)return 0; int cnt = 0; for (int i = 0; i < s.length();i++) { ifsub(s, i, i, cnt);//判断奇数情况 ifsub(s, i, i+1, cnt);//判断偶数情况 } return cnt; }
参考:
https://discuss.leetcode.com/topic/96884/very-simple-java-solution-with-detail-explanation
[leetcode-647-Palindromic Substrings]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。