647. Palindromic Substrings

647. Palindromic Substrings

1. 题目描述
题目链接

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.

2. 题目分析
找出字符串中所以回文串,并且统计数量。回文串就是,从左边遍历和从右边遍历等到的字符串是一样的就叫回文串,如aba,abba等。从我的举例中可以看出,回文串会有两种格式,一种是aba这种,关于中间一个字符对称,另一个种是abba,关于中间一条线对称。

3. 解决思路
既然回文串根据中间“对称”的,那么我们可以从一段字符串的中间,向左右两边遍历比较,如果相等,则说明这是一个回文串,数量加1。但这里面要注意一个细节,就是abba型的字符串,先用中间字符跟右边第一个字符比较,如果相等,再往左右两边比较;如果不相等,则使用aba型的字符串比较方式,直接中间的左边第一个和右边第一个进行比较。

4. 代码实现(java)

package com.algorithm.leetcode.dynamicAllocation;

/**
 * Created by 凌 on 2018/12/14.
 * 描述:
 */
public class CountSubstrings {
    public static void main(String[] args) {
        String s = "abbcd";
//        String s = "abacd";
//        String s = "aaa";
        int result = countSubstrings(s);
        System.out.println(result);
    }
    public static int countSubstrings(String s) {
        if (s == null || s.isEmpty()){
            return 0;
        }
        int count = s.length();

        int mid = 0;
        int left = mid;
        int right = mid + 1;
        int len = s.length();
        while (mid < len - 1) {
            //如abbcd
            if (s.charAt(left) == s.charAt(right)){
                while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                    count++;
                    left--;
                    right++;
                }
            }
            //abacd、aaa
            left = mid - 1;
            right = mid + 1;
            if (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                    count++;
                    left--;
                    right++;
                }
            }
            mid++;
            left = mid;
            right = mid + 1;
        }
        return count;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值