LeetCode-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.

 

翻译:

给定一个字符串,你的任务是计算在字符串中有多少回文的子字符串。

由相同字符组成的带有不同起始下标和终止下标的子字符串都算作不同的子字符串。

例子 1:

输入: "abc"
输出: 3
解释: 3个回文字符串: "a", "b", "c".

例子 2:

输入: "aaa"
输出: 6
解释: 6个回文字符串: "a", "a", "a", "aa", "aa", "aaa".

注意:

  1. 输入的字符串长度不超过1000。

 

思路:

从每一个字符开始判断,分别将它作为回文字符的中间字符来判断它左右两边的字符是否相等,由此来判断回文子字符,同时,注意回文字符串分为奇数和偶数两种形式。参见http://www.cnblogs.com/grandyang/p/7404777.html

 

C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
	void count(string s, int i, int j, int& res) {
		while (i >= 0 && j < s.size() && s[i] == s[j]){
			i--; j++; res++;
		}
	}

	int countSubstrings(string s) {
		if (s.empty())
			return 0;
		int res=0;
		for (int i = 0; i < s.size(); i++) {
			count(s, i, i, res);
			count(s, i, i + 1, res);
		}
		return res;
	}
};

int main()
{
	Solution s;
	string str = "aaa";
	int result = s.countSubstrings(str);
	cout << result << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值