Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class Solution {
- public:
- string longestPalindrome(string s) {
- int length = 0, initial = 0;
- for (int i = 0; i < s.size(); ++i)
- {
- int len1 = getPalindromeLength(s, i, i);
- int len2 = getPalindromeLength(s, i, i + 1);
- int len = (len1 > len2) ? len1 : len2;
- if (len > length)
- {
- length = len;
- initial = i - (length - 1) / 2;
- }
- }
- return s.substr(initial, length);
- }
- int getPalindromeLength(string s, int low, int high)
- {
- while (low >= 0 && high < s.size() && s[low] == s[high])
- {
- --low; ++high;
- }
- return (high - low) - 1;
- }
- };
- int main(void)
- {
- Solution s;
- cout << s.longestPalindrome("babad") << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment