版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lcharon/article/details/76647323
[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;
}