Leetcode 5. Longest Palindromic Substring
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 5. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
5. Longest Palindromic Substring
- Total Accepted: 128442
- Total Submissions: 539273
- Difficulty: Medium
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路:Palindromic,就是回文的意思。一般回文字符串是从中间向两边展开,看中心的左边是否完全等于中心的右边。
代码:代码中有2处改进,需要体会。
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 int minbegin = 0, maxlen = 1; 5 for (int i = 0; i < s.size(); ) { 6 //改进1 7 if (i + maxlen / 2 >= s.size()) break; 8 int begin = i, end = i; 9 while (end < s.size() - 1 && s[end] == s[end+1]) end++; 10 //改进2 11 i = end + 1; 12 while (end < s.size() && begin >=0 && s[begin] == s[end]){ 13 begin--; 14 end++; 15 } 16 int curlen = end - begin - 1; 17 if (curlen > maxlen) { 18 maxlen = curlen; 19 minbegin = begin + 1; 20 } 21 } 22 return s.substr(minbegin,maxlen); 23 } 24 };
以上是关于Leetcode 5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
leetcode--5. Longest Palindromic Substring
#Leetcode# 5. Longest Palindromic Substring
LeetCode题解 #5 Longest Palindromic Substring
[LeetCode] 5 Longest Palindromic Substring