Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <string>
- using namespace std;
- class Solution {
- public:
- string longestPalindrome(string s) {
- string result;
- int max = 0;
- for(int i = 1; i< s.size()-1; i++) {
- if ( s.at(i-1)==s.at(i+1) ) {
- string value = Palindrome(s, i-1, i+1);
- if (max < static_cast<int>(value.size()) ) {
- result = value;
- max = value.size();
- }
- }
- if( s.at(i-1) == s.at(i) ) {
- string value = Palindrome(s, i-1, i);
- if (max < static_cast<int>(value.size()) ) {
- result = value;
- max = value.size();
- }
- }
- if( s.at(i) == s.at(i+1) ) {
- string value = Palindrome(s, i, i+1);
- if (max < static_cast<int>(value.size()) ) {
- result = value;
- max = value.size();
- }
- }
- }
- return result;
- }
- string Palindrome(string s, int left, int right) {
- int min_size = std::min(left, static_cast<int>(s.size()-(right+1)));
- for (int i=0; i<=min_size; i++ ) {
- if (s.at(left) == s.at(right)) {
- left--;
- right++;
- }
- else break;
- }
- left++;
- string_view total = s.substr(left, right-left);
- return string(total);
- }
- };
- int main()
- {
- Solution sol;
- string s;
- {
- s = "AbAaaSTRoRTSaaF";
- cout << sol.longestPalindrome(s) << endl;
- }
- {
- s = "babad";
- cout << sol.longestPalindrome(s) << endl;
- }
- {
- s = "cbbd";
- cout << sol.longestPalindrome(s) << endl;
- }
- {
- s = "cbdd";
- cout << sol.longestPalindrome(s) << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement