[LeetCode]647. Palindromic Substrings
阿新 • • 發佈:2018-12-23
[LeetCode]647. Palindromic Substrings
題目描述
思路
- 簡單暴力遍歷
- 減少比較次數,將外層迴圈遍歷的每個元素當作中間值,左右分別伸展,考慮奇數和偶數長度的字串情況
程式碼
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
/*
bool isPalind(string str, int start, int end) {
while (start < end) {
if (str[start] != str[end]) return false;
++start, --end;
}
return true;
}
int countSubstrings(string s) {
int res = 0;
for (int start = 0; start < s.size(); ++start)
for (int end = start; end < s.size(); ++end )
if (isPalind(s, start, end)) ++res;
return res;
}
*/
int countSubstrings(string s) {
int res = 0;
for (int mid = 0; mid < s.size(); ++mid) {
for (int offset = 0; mid - offset >= 0 && mid + offset < s.size() && s[mid - offset] == s[mid + offset]; ++offset)
++res;
for (int offset = 0; mid - offset - 1 >= 0 && mid + offset < s.size() && s[mid - offset - 1] == s[mid + offset]; ++offset)
++res;
}
return res;
}
};
int main() {
Solution s;
cout << s.countSubstrings("aaa") << endl;
system("pause");
return 0;
}