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".
写个判断回文字符串的函数,计数。简单粗暴。
class Solution {
public:
int countSubstrings(string s) {
vector<char>str(s.size(), '0');
for (int i = 0; s[i] != '\0'; i++)
{
str[i] = s[i];
}
int res = 0;
for (int j = 0; j < str.size(); j++)
{
for (int k = j; k < str.size(); k++)
{
if (isPalindromic(str, j, k))
res++;
}
}
return res;
}
bool isPalindromic(vector<char> &str, int start, int end)
{
while (start < end)
{
if (str[start] != str[end])
{
return false;
}
start++;
end--;
}
return true;
}
};
网友评论