LeetCode 647 Palindromic Substrings
来源:互联网 发布:mac os x 10.9.5 下载 编辑:程序博客网 时间:2024/06/04 18:48
题目:
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.
题意:
给一个字符串,要求数出这个字符串的子串中有多少个是回文串,不同起点的子串即为不同。
字符串长度不超过1000。
对于每一个字符,它本身一定是一个回文串,所以我们可以枚举每一个字符作为回文串中心,向外扩展,extendPalindrome函数可以借鉴题目5.Longest Palindromic Substring,分为单个中心和两个字符为中心的情况来讨论,向两边来扩展,每次统计结果+1即可。
代码如下:
class Solution { private int extendPalind (String s, int l, int r) { int sum = 0; while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { sum ++; l --; r ++; } return sum; } public int countSubstrings(String s) { int ans = 0; for (int i = 0; i < s.length(); i ++) { ans += extendPalind(s, i, i); if (i + 1 < s.length() && s.charAt(i) == s.charAt(i+1)) { ans += extendPalind(s, i, i + 1); } } return ans; }}
阅读全文
0 0
- LeetCode 647 Palindromic Substrings
- LeetCode 647 Palindromic Substrings
- 【Leetcode-Medium-647】Palindromic Substrings
- LeetCode 647 : Palindromic Substrings(java)
- 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-Palindromic Substrings
- LeetCode:Palindromic Substrings
- [LeetCode] 647. Palindromic Substrings
- LeetCode--Palindromic Substrings
- VMware 安装Centos6.5
- SPFA算法——最短路径
- win10使用Ubuntu子系统并添加桌面
- 58人被抓!腾讯守护者协助警方斩断DDoS黑产全链条
- 十年抗争,十亿欧元罚款,英特尔反垄断案近期重审
- LeetCode 647 Palindromic Substrings
- 百度 UNIT 技术负责人揭秘:如何让你的对话系统更智能
- 我们去参加了暴风的风迷节,它和乐视的乐迷节有什么区别?
- 亚马逊在纽约建配送中心 2250名员工与机器人工作
- js 使用ajax进行文件上传并获取上传进度案例
- ITK4.7在vs2012环境下配置与编译
- 实验三
- mysql-数据类型
- 纳尼?!Apple Watch还可以用于棒球比赛作弊!