給定一個字符串,你的任務是計算這個字符串中有多少個迴文子串。
具有不同開始位置或結束位置的子串,即使是由相同的字符組成,也會被計爲是不同的子串。
思路
啊啊啊,注意一點就可以,一個串是子串,只有其中的子串都是迴文串纔算得上是迴文串,所以說,如果一個串不是迴文串,那麼也沒有必要繼續向後找了,
另一點需要注意的就是尋找回文串的時候,肯定要從中間向兩邊去找,通過定義left,right來解決對於迴文串是奇數長度與偶數長度的情況。
代碼
class Solution {
public:
int countSubstrings(string s) {
int cnt = 0;
for (int i = 0; i < s.size(); i++) {
cnt += count(s, i, i);
cnt += count(s, i, i + 1);
}
return cnt;
}
int count(const string& s,int start, int end) {
int cnt = 0;
while (start >= 0 && end < s.size() && s[start] == s[end]) --start, ++end,++cnt;
return cnt;
}
};