-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.最长回文子串.cs
67 lines (56 loc) · 1.41 KB
/
5.最长回文子串.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode.cn id=5 lang=csharp
*
* [5] 最长回文子串
*/
// @lc code=start
public class Solution
{
public string LongestPalindrome(string s)
{
int ansVal = 1;
int ansLeft = 0, ansRight = 0;
for (int i = 1; i < s.Length - 1; i++)
{
int nowAns = 0;
int left = i - 1, right = i + 1;
while (left >= 0 && right < s.Length)
{
if (s[left] == s[right])
{
nowAns += 2;
left--; right++;
}
else break;
}
if (nowAns > ansVal)
{
ansVal = nowAns;
ansLeft = left + 1;
ansRight = right - 1;
}
}
for (int i = 1; i < s.Length; i++)
{
int nowAns = 0;
int left = i - 1, right = i;
while (left >= 0 && right < s.Length)
{
if (s[left] == s[right])
{
nowAns += 2;
left--; right++;
}
else break;
}
if (nowAns > ansVal)
{
ansVal = nowAns;
ansLeft = left + 1;
ansRight = right - 1;
}
}
return s.Substring(ansLeft, ansRight - ansLeft + 1);
}
}
// @lc code=end