题目:
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.
翻译:
给定一个字符串,你的任务是计算在字符串中有多少回文的子字符串。
由相同字符组成的带有不同起始下标和终止下标的子字符串都算作不同的子字符串。
例子 1:
输入: "abc" 输出: 3 解释: 3个回文字符串: "a", "b", "c".
例子 2:
输入: "aaa" 输出: 6 解释: 6个回文字符串: "a", "a", "a", "aa", "aa", "aaa".
注意:
- 输入的字符串长度不超过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;
}