LeetCode:647. Palindromic Substrings
来源:互联网 发布:淘宝网品种销量排行榜 编辑:程序博客网 时间:2024/05/16 12:54
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.
题意:求字符串中回环子串的个数
分析:假设A[left,right]是回环的,如果A[left-1]==A[right+1],必然A[left-1,right+1]也是回环的。
因此必须找到一个遍历的顺序。只要找到回环子串的对称轴,然后向外扩展,就可以遍历解空间,需要注意回环串长度是奇数的(从长度为1的子串遍历),以及回环串长度是偶数的(从长度是2的子串遍历)。
代码如下:
class Solution { public int countSubstrings(String s) { if(s==null||s.length()==0) return 0; LinkedList<Integer> left=new LinkedList<Integer>(); LinkedList<Integer> right=new LinkedList<Integer>(); left.addFirst(0); right.addFirst(0); for(int i=1;i<s.length();i++){ left.addFirst(i); right.addFirst(i); if(s.charAt(i)==s.charAt(i-1)) { left.addFirst(i-1); right.addFirst(i); } } int count=left.size(); while(left.size()>0){ int l=left.removeLast(); int r=right.removeLast(); while(l-1>=0&&r+1<s.length()&&s.charAt(l-1)==s.charAt(r+1)){ count++; l--; r++; } } return count; }}
阅读全文
0 0
- [leetcode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode]647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode] 647. Palindromic Substrings
- 【LeetCode】647. Palindromic Substrings
- Leetcode 647. Palindromic Substrings
- LeetCode:647. Palindromic Substrings
- #leetcode#647. Palindromic Substrings
- [LeetCode] 647. Palindromic Substrings
- leetcode 647. Palindromic Substrings
- [LeetCode]647. Palindromic Substrings
- LeetCode:M-647. Palindromic Substrings
- LeetCode 647. Palindromic Substrings[Medium]
- Dynamic Programing -- Leetcode problem 647. Palindromic Substrings
- Leetcode 647.Palindromic Substrings(算法分析week15)
- LeetCode-Palindromic Substrings
- LeetCode:Palindromic Substrings
- Android中WebView渲染显示web页面
- K尾相等数
- [POJ2485]Highways
- linux下系统启动时,几个配置文件 /etc/profile、~/.bash_profile 等几个文件的执行过程,先后顺序
- Java中的String、正则表达式
- LeetCode:647. Palindromic Substrings
- linux安装mysql
- Qt使用QWebengineView导致花屏和黑屏现象
- 测试用例实例--常见功能测试点
- LeetCode 268. Missing Number
- 【Unity与23种设计模式】迭代器模式(Iterator)
- Cordova 自定义插件(Android)
- redis集群搭建详细指导(图文介绍)
- 值的交换