LeetCode 647. Palindromic Substrings(647. 回文子串)

647. Palindromic Substringsthis

Given a string, your task is to count how many palindromic substrings in this string.spa

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.指针

  • Example 1:

Input: "abc"code

Output: 3blog

Explanation: Three palindromic strings: "a", "b", "c".leetcode

  • Example 2:

Input: "aaa"字符串

Output: 6get

Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".input

Note:The input string length won't exceed 1000.string

解题思路:

使用中心扩展方法,每一个字符都是一个中心,或者两个相邻同样的字符是一个中心,而后向左右分别递进判断可否造成回文

举个🌰

  好比字符串是    a   b   a

  遍历字符串   <-⬆->             回文子串 a  左边没有数据因此只有这一个

                      <-⬆->         回文子串 b  一个指针向左走一个指针向右走 判断是否还有对应的子串(aba), 左边 a 右边 a 能造成字串,再走没有数据

                        <-⬆->     回文字串 a 右边没有数据因此结束

  根据上面的流程 最终的字串为  a,b, aba, a 共4个

 

  固然还有两个字符同样的状况

  好比字符串是   a   b   b   a

  这样就须要      <-⬆  ⬆->      从中间两个向外判断是否能造成回文子串  

参考代码:

class Solution {
    // 回文字串数量
    int count = 0;
    public int countSubstrings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        for (int i = 0; i < s.length(); i++) {
            // aba -> i 为 b位置
            helper(s,i,i);
            // abba -> i 为第一个b位置
            helper(s,i,i+1);
        }
        return count;
    }

    private void helper(String s, int left, int right) {
        while (left >= 0 && right <= s.length() - 1 && s.charAt(left) == s.charAt(right)) {
            count++;
            left--;
            right++;
        }
    }
}
相关文章
相关标签/搜索