Leet code problem 5 Longest Palindromic Substring
Posted nosaferyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet code problem 5 Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
class Solution { public: string longestPalindrome(string s) { int x = -1; int l = -1; for (int i = 0; i < (int)s.size(); ++i){ int left = i; int right = i; while (left >= 0 && right < s.size() && s[left] == s[right]){ --left; ++right; } int tl = right - left - 1; if (tl > l){ l = tl; x = left+1; } left = i-1; right = i; while (left >= 0 && right < s.size() && s[left] == s[right]){ --left; ++right; } tl = right - left - 1; if (tl > l){ l = tl; x = left+1; } } if (l > -1){ return s.substr(x, l); } return ""; } };
号称还有O(n)的算法:
http://articles.leetcode.com/longest-palindromic-substring-part-ii/
后面再研究,
以上是关于Leet code problem 5 Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章