Leetcode 5. Longest Palindromic Substring (Medium) (cpp)

来源:互联网 发布:java web有什么好书 编辑:程序博客网 时间:2024/06/09 20:36

Leetcode 5. Longest Palindromic Substring (Medium) (cpp)

Tag: String

Difficulty: Medium


/*5. Longest Palindromic Substring (Medium)Given a string S, find the longest palindromic substring in S. You may assume that the maximumlength of S is 1000, and there exists one unique longest palindromic substring.*/class Solution {public:string longestPalindrome(string s) {string res;int _size = s.length(), l_max = 0, len_max = 0, l, r;for (int i = 0; i < _size && _size - i > len_max / 2;) {l = r = i;while (r < _size - 1 && s[r] == s[r + 1]) {r++;}i = r + 1;while (l > 0 && r < _size - 1 && s[l - 1] == s[r + 1]) {l--;r++;}if (r - l + 1 > len_max) {len_max = r - l + 1;l_max = l;}}return s.substr(l_max, len_max);}};


0 0
原创粉丝点击