好久没接触过的涉及回文字符串的题目:LeetCode 647. 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:
- The input string length won't exceed 1000.
要紧捉住回文字符串的特点:中心对称。以某个字符为中心来判断左右是否对称。
class Solution {
public:
int countSubstrings(string s) {
int count = 0;
int len = s.length();
//aba式的回文字符串
for (int i = 0; i < len; i++) {
for (int j = 0; i - j >= 0 && i + j < len; j++) {
if (s[i - j] == s[i + j]) {
count++;
} else {
break;
}
}
}
//abba式的回文字符串
for (int i = 0; i < len; i++) {
for (int j = 0; i - j >= 0 && i + j + 1 < len; j++) {
if (s[i - j] == s[i + j + 1]) {
count++;
} else {
break;
}
}
}
return count;
}
};