-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0005-Longest-palindromic-substring.cs
More file actions
47 lines (38 loc) · 1.1 KB
/
0005-Longest-palindromic-substring.cs
File metadata and controls
47 lines (38 loc) · 1.1 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0005.Longest_palindromic_substring
{
public class _0005_Longest_palindromic_substring
{
public string LongestPalindrome(string s)
{
if (s.Length <= 1) return s;
int left = 0, odd, even, curr, max = 0;
for (int i = 0; i < s.Length; i++)
{
// ex: 121
odd = Palindrome(s, i, i);
// ex: 1221
even = Palindrome(s, i, i + 1);
// compare
curr = (odd > even ? odd : even);
if (curr > max)
{
max = curr;
left = i - (max - 1) / 2;
}
}
return s.Substring(left, max);
}
private int Palindrome(string s, int left, int right)
{
while (left >= 0 && right < s.Length && s[left] == s[right])
{
left--;
right++;
}
return right - left - 1;
}
}
}