647. Palindromic Substrings 回文子串

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:

  1. The input string length won't exceed 1000.

题意:给出一个字符串,找出它一共有多少个是回文数的子字符串,(子字符串相同但起始坐标不同的当成两个子字符串)。

思路:遍历字符串个每个字符,以字符本身为对称轴,向其左右两边一直扩散,直到两边不再是回文数;

同时以遍历的字符与右边紧邻的字符为对称轴,向其左右两边一直扩散,直到两边不再是回文数,如图所示:

代码:

class Solution {
    int count =0;
    public int countSubstrings(String s) {
        int len = s.length();
        for(int i=0;i<len;i++){
            getPalindromic(s,i,i); //当前字符为对称轴
            getPalindromic(s,i,i+1); //以两个字符为对称轴
        }
        return count;
    }
    
    public void getPalindromic(String str, int left, int right){
        while(left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)){
            left--;
            right++;
            count++;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值