美文网首页
# 647. 回文子串(647. Palindromic Sub

# 647. 回文子串(647. Palindromic Sub

作者: 李小争 | 来源:发表于2020-08-19 23:15 被阅读0次

题目地址:647. 回文子串
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: 3
Explanation: Three palindromic strings: "a", "b", "c".
  • Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

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

解题思路:

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

举个🌰

  比如字符串是   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++;
        }
    }
}

相关文章

  • # 647. 回文子串(647. Palindromic Sub

    题目地址:647. 回文子串Given a string, your task is to count how m...

  • 647. Palindromic Substrings 回文子串

    Given a string, your task is to count how many palindromi...

  • 回文类题目总结

    起因在于写647. Palindromic Substrings时写错了,感觉跟其他回文题搞混了。特地总结一下,尤...

  • 两道回文子串的解法

    两道题分别是:leetcode 5. 最长回文子串 和 647. 回文子串 先看647题 找到一个字符串中所有的回...

  • 647. 回文子串

    思路:直接暴力来列举出所有的回文中心,然后一个一个的去判断是不是能构成回文串判断索引为left和right的值是不...

  • 647.回文子串

    647.回文子串 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。具有不同开始位置或结束位置的子串,即...

  • 647. 回文子串

    给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。具有不同开始位置或结束位置的子串,即使是由相同的字符组...

  • 647. 回文子串

    这道题目和求解最长回文子串的题目是一样的框架结构, 不同的地方在于这到题目统计的是总数.

  • 647. 回文子串

    解法 动态规划解法 中心扩展思想

  • 647. 回文子串

    一 题目: 二 思路: 动态规划法 状态:dp[i][j] 表示字符串s在[i,j]区间的子串是否是一个回文串。状...

网友评论

      本文标题:# 647. 回文子串(647. Palindromic Sub

      本文链接:https://www.haomeiwen.com/subject/bqjjjktx.html