LeetCode 647. Kaibunko skewer (Palindromic Substrings)

647. Kaibunko skewer
647. Palindromic Substrings

Title Description
Given a string, your task is to calculate how many string palindrome substring.

Substring having a different start position or the end position, even by the same characters will be counted as a different string.

LeetCode647. Palindromic Substrings中等

Example 1:

Input: "ABC"
Output: 3
Explanation: 3 palindrome substring: "a", "b" , "c".

Example 2:

Input: "AAA"
Output: 6
Description: 6 palindromic substring: "a", "a" , "a", "aa", "aa", "aaa".

note:

  • Length of the input string is not more than 1000.

Java implementation

class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            count += extractPalindrome(s, i, i);
            count += extractPalindrome(s, i, i + 1);
        }
        return count;
    }

    public int extractPalindrome(String s, int left, int right) {
        int count = 0;
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            count++;
            left--;
            right++;
        }
        return count;
    }
}

Similar topics

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/10926473.html