- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 70 lines of C++ from the credited upstream file abc237_c.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1#include <iostream>2#include <vector>3 4using namespace std;5 6bool is_palindrome(string str) {7 if (str.size() < 2) {8 return true;9 }10 11 unsigned long mid = str.size() / 2;12 unsigned long f = mid - 1, b = mid + str.size() % 2;13 unsigned long i = 0, j = 1;14 while (i < j && i < mid) {15 j = str.size() - i - 1;16 17 if (str[i] != str[j] || str[f - i] != str[b + i]) {18 return false;19 }20 21 i++;22 }23 24 return true;25}26 27int main() {28 string s = "";29 cin >> s;30 31 if (is_palindrome(s)) {32 cout << "Yes" << endl;33 return 0;34 }35 36 unsigned long front = 0;37 unsigned long back = 0;38 unsigned long i = 0, j = s.size() - 1;39 unsigned long f_add = 1, b_add = 1;40 while (i < j) {41 if (f_add == 0 && b_add == 0) {42 break;43 }44 if (s[i] != 'a') {45 f_add = 0;46 }47 if (s[j] != 'a') {48 b_add = 0;49 }50 51 front += f_add;52 back += b_add;53 54 i += f_add;55 j -= b_add;56 }57 58 if (front > back) {59 cout << "No" << endl;60 return 0;61 }62 63 s = s.substr(front, s.size() - front - back);64 if (is_palindrome(s)) {65 cout << "Yes" << endl;66 return 0;67 }68 69 cout << "No" << endl;70}