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:

  1. 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;    }}


原创粉丝点击