LeetCode5.最长回文子串
题目
代码
暴力法
时间复杂度:O(n3)
public class Solution
{
public string LongestPalindrome(string s)
{
string result = "";
for (int i = 0; i < s.Length; i++)
{
for (int j = i; j < s.Length; j++)
{
int left = i, right = j;
bool isPalindromic = true;
while (left < right)
{
if (s[left++] != s[right--])
{
isPalindromic = false;
break;
}
}
if (isPalindromic)
{
int len = j - i + 1;
if (len > result.Length)
result = s.Substring(i, len);
}
}
}
}
}
中心法扩展法
时间复杂度:O(n3)
public class Solution
{
public string LongestPalindrome(string s)
{
if (s.Length < 2)
return s;
string result = "";
int n = s.Length;
for (int i = 0; i < n; i++)
{
int left = i, right = i;
while (left >= 0 && right < n)
{
if (s[left] != s[right])
break;
left--;
right++;
}
int len = right - left - 1;
if (len > result.Length)
result = s.Substring(left+1, len);
}
for (int i = 0; i < n; i++)
{
int left = i, right = i;
while (left >= 0 && right < n)
{
if (s[left] != s[right])
break;
left--;
right++;
}
int len = right - left - 1;
if (len > result.Length)
result = s.Substring(left+1, len);
}
return result;
}
}
把两个for放在了一起
public class Solution
{
public string LongestPalindrome(string s)
{
if (s.Length < 2)
return s;
string result = "";
int n = s.Length;
int left, right, len;
for (int i = 0; i < n; i++)
for (int j = 0; j < 2; j++)
{
left = i;
right = i + j;
while (left >= 0 && right < n)
{
if (s[left] != s[right])
break;
left--;
right++;
}
len = right - left - 1;
if (len > result.Length)
result = s.Substring(left + 1, len);
}
return result;
}
}
中心扩展法的另一种想法,即中心可以取在两个数中间。
时间复杂度:O(n2)
public class Solution
{
public string LongestPalindrome(string s)
{
if (s.Length < 2)
return s;
string result = "";
int n = s.Length;
int end = 2 * n - 1;
for (int i = 0; i < end; i++)
{
double mid = i / 2.0;
int left = (int)(Math.Floor(mid));
int right = (int)(Math.Ceiling(mid));
while (left >= 0 && right < n)
{
if (s[left] != s[right])
break;
left--;
right++;
}
int len = right - left - 1;
if (len > result.Length)
result = s.Substring(left + 1, len);
}
return result;
}
}
000