LeetCode 647. Palindromic Substrings

参考资料:《代码随想录》,力扣官方解答

647. Palindromic Substrings
Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

 

Example 1:

Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:

Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
 

Constraints:

1 <= s.length <= 1000
s consists of lowercase English letters.

思路:
注意到:回文串的中心要么是一个字符,要么是两个字符。
枚举回文串的中心,然后向左右两边扩,扩的同时记得计数。

附加:这道题与 LeetCode5有异曲同工之妙。

class Solution {
    int count=0;// global var
    public int countSubstrings(String s) {
        if(s==null || s.length()==0){
            return 0;
        }

        char[] str = s.toCharArray();
        for(int i=0;i<str.length;i++){
            extend(str,i,i);// 计数 有多少回文串以str[i]为中心
            extend(str,i,i+1);// 计数 有多少回文串以str[i,i+1]为中心
        }
    return count;
    }

    public void extend(char[] str, int l, int r){
        while(l>=0 &&r<str.length && str[l]==str[r]){
            count++;
            l--;
            r++;
        }
    }
}

你可能感兴趣的:(数据结构与算法,leetcode,java,算法)