Problem:
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.
思路:
Solution (C++):
int countSubstrings(string s) {
int m = s.length(), count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 1; j <= m-i; ++j) {
if (isPalindrome(s.substr(i, j))) count++;
}
}
return count;
}
bool isPalindrome(string str) {
int n = str.length();
if (n == 1) return true;
for (int i = 0; i <= (n-1)/2; ++i) {
if (str[i] != str[n-1-i]) return false;
}
return true;
}
性能:
Runtime: 992 ms Memory Usage: 456.1 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB