Re: [闲聊] 每日LeetCode

楼主: z2147483648 (溢伤了喇)   2023-10-28 01:28:32
: 5. Longest Palindromic Substring
: 给一个字串s,回传最长的子字串,其顺序跟倒序长一样。
: Input: s = "babad"
: Output: "bab" 或 "aba"
想法:
感觉可以用DP写,但我DP不好@@
改用回文特性中心扩散法
从中间检查两边index+i, index-i是否相等,来判断是否是回文
如果是回文的话顺便算一下是否是目前最大
然后迭代每个index找出最大值
奇数很好懂 就是index-i, index+i
偶数推了一下 每次检查index-i, index+i-1
如果不是就break(利用odd_continue/even_continue两个Flag控制)
Python死脑筋的用了while if 写来写去,不小心遇到边界陷阱
C++改用function包起来简单美观多了
========== Python
class Solution:
def longestPalindrome(self, s: str) -> str:
maxLen = 0
maxret = ""
for i in range(len(s)):
j = 0
odd_continue = True
even_continue = True
while(i - j >= 0 and i + j - 1 < len(s)):
if (odd_continue and i+j < len(s) and s[i-j] == s[i+j]):
if maxLen < 2*j + 1:
maxret = s[i-j: i+j+1]
maxLen = 2*j + 1
else:
odd_continue = False
if (j > 0):
if (even_continue and s[i-j] == s[i+j-1]):
if maxLen < 2*j:
maxret = s[i-j: i+j]
maxLen = 2*j
else:
even_continue = False
if (not odd_continue and not even_continue):
break
j += 1
return maxret
=========== C++
class Solution {
public:
string longestPalindrome(string s) {
int maxLen = 0;
string maxString = "";
for (int i = 0; i < s.size(); ++i)
{
vector<int> res = findMaxPalindrome(s, i, i);
int st = res[0];
int end = res[1];
if (end - st + 1 > maxLen)
{
maxLen = end - st + 1;
maxString = s.substr(st, end-st+1);
}
res = findMaxPalindrome(s, i, i+1);
st = res[0];
end = res[1];
if (end - st + 1 > maxLen)
{
maxLen = end - st + 1;
maxString = s.substr(st, end-st+1);
}
}
return maxString;
}
vector<int> findMaxPalindrome(string s, int center, int center2)
{
int count = 0;
while(center >= 0 && center2 < s.size())
{
if (s[center] == s[center2])
{
count++;
center
作者: wwndbk (黑人问号)   2023-10-28 01:34:00
大师
楼主: z2147483648 (溢伤了喇)   2023-10-28 02:04:00
楼上才是大师

Links booklink

Contact Us: admin [ a t ] ucptt.com