iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
Software Development

LeetCode刷題日記系列 第 12

【Day 12】#5 - Longest Palindromic Substring

  • 分享至 

  • xImage
  •  

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

解析

此題要求找出最長左右對稱的子字串。

解法

public String longestPalindrome(String s) {
    if (s == null || s.length() < 1) return "";
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(s, i, i + 1);
        int len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
    int L = left, R = right;
    while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return R - L - 1;
}

備註


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


上一篇
【Day 11】#19 - Remove Nth Node From End of List
下一篇
【Day 13】#200 - Number of Islands
系列文
LeetCode刷題日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
yclin925
iT邦新手 5 級 ‧ 2022-12-01 11:16:17

感謝樓主分享,好奇這樣跑分秒數約多少?
我用2次迴圈,內層迴圈用find方法找頭尾相符字元,跑分約0.8S~1.8S
https://www.youtube.com/watch?v=yIVwQ8QmtOQ

hyj1116 iT邦新手 4 級 ‧ 2023-08-01 23:09:03 檢舉

Runtime大約只要15ms左右
https://ithelp.ithome.com.tw/upload/images/20230801/2010000923EPvFxm3O.png

我要留言

立即登入留言