LeetCode:M-647. Palindromic Substrings

来源:互联网 发布:编写java 用什么软件 编辑:程序博客网 时间:2024/06/05 10:14

LeetCode链接


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.

class Solution {    int cnt=0;    public int countSubstrings(String s) {        if(s==null || s.length()==0)            return 0;                       for(int i=0; i<s.length(); i++){            extendPalindrome(s, i, i);//自己也算一个,奇数个数的回文扩展                        extendPalindrome(s, i, i+1);//偶数个数的回文扩展        }                         return cnt;    }    void extendPalindrome(String str, int s, int e){        while(s>=0 && e<str.length() && str.charAt(s)==str.charAt(e)){            s--;            e++;            cnt++;        }    }}


原创粉丝点击