(LeetCode Day1)求字符串里回文字符串的个数

问题

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.

思路

从中心向左右扩展,核心是确定中心center,对于奇偶长度的字符串都是一个道理

先确定字符串里哪一个字符作为你的中心,确定之后,就向左右扩展一个单位,然后判断你的左右位置是否越界,因为位置不可能为负数,也不可能大于你的字符串长度,再判断你的左右字符是否相等,若相等就count++,左右继续移动,若不相等就换中心点。
偶数的话最初就把你的left和right设为两个相邻值,判断条件一样。

代码


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++) {
			kuozhan(s,i,i);
			kuozhan(s, i, i+1);
    		
		}
    	
    	
    	
    	return count;
    }
    
   void kuozhan(String s,int left, int right) {
    	while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)) {
    		count++;
    		left--;
    		right++;
    	}
    	
    }

时间复杂度

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值