(LeetCode) 5. Longest Palindromic Substring

文章目录

  1. 1. Original URL: 5. Longest Palindromic Substring
  2. 2. My solutions:
    1. 2.1. With C++:

>

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.

Difficulty: Medium
Tags: String

Original URL: 5. Longest Palindromic Substring

My solutions:

With C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
string longestPalindrome(string s) {
int m = 0,x = 0,li = 0;
int n = s.length();
for(int i=0; i < n ;i++)
{
for(int j=i; j < n ;j++)
{
if(s[i] == s[j])
{
for(int k=0;k<=(j-i)/2;k++)
{
if(s[i+k] != s[j-k])
{break;}
else if(i+k == j-k)
{x = 2*k+1;}
else if(i+k+1==j-k)
{x = 2*(k+1);}
if(x>m)
{m = x;
li = i;
}
}
}
}
}
return s.substr(li,m);
}
};

See my 30+ solutions of LeetCode on GitHub