【Leetcode】647. 回文子串的数量(Palindromic Substrings)

Leetcode - 647 Palindromic Substrings (Medium)

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

解题思路:依次以每个字符为中心向外扩展,计算回文子串的数量。

int count = 0;
    public int countSubstrings(String s) {
        for (int i = 0; i < s.length(); i++) {
            extendPalindrome(s, i, i);
            extendPalindrome(s, i, i + 1);
        }
        return count;
    }
    public void extendPalindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--; right++; count++;
        }
    }

你可能感兴趣的:(LeetCode,字符串)