Skip to content

Commit

Permalink
5. Longest Palindromic Substring
Browse files Browse the repository at this point in the history
  • Loading branch information
blueBlue0102 committed Nov 20, 2024
1 parent c2392f0 commit 853d606
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package leetcode

func LongestPalindromicSubstring(s string) string {
longestLen := 0
longestString := ""
runeSlice := []rune(s)
for index := range runeSlice {
// odd mode
length := 1
leftIndex := index - 1
rightIndex := index + 1
for leftIndex >= 0 && rightIndex < len(s) {
if runeSlice[leftIndex] == runeSlice[rightIndex] {
length += 2
leftIndex--
rightIndex++
} else {
break
}
}
if length > longestLen {
longestLen = length
longestString = string(runeSlice[leftIndex+1 : rightIndex])
}
// even mode
length = 0
leftIndex = index
rightIndex = index + 1
for leftIndex >= 0 && rightIndex < len(s) {
if runeSlice[leftIndex] == runeSlice[rightIndex] {
length += 2
leftIndex--
rightIndex++
} else {
break
}
}

if length > longestLen {
longestLen = length
longestString = string(runeSlice[leftIndex+1 : rightIndex])
}
}

return longestString
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package leetcode

import (
"reflect"
"testing"
)

// 填入 function input type
type parameters0005 struct {
s string
}

func TestLongestPalindromicSubstring(t *testing.T) {
tests := []struct {
parameters0005
// 填入 function output type
ans string
}{
// 填入 test case
{
parameters0005{"babad"},
"bab",
},
{
parameters0005{"cbbd"},
"bb",
},
{
parameters0005{"abcd"},
"a",
},
}

for _, test := range tests {
t.Run("Test LongestPalindromicSubstring", func(t *testing.T) {
// 完整輸入參數
result := LongestPalindromicSubstring(test.parameters0005.s)
// compare 的方式需視情況調整
// 由於答案可能不只一組,所以用長度來辨別
if !reflect.DeepEqual(len(result), len(test.ans)) {
t.Errorf("LongestPalindromicSubstring(%+v) got %+v, want %+v", test.parameters0005, result, test.ans)
}
})
}
}
20 changes: 20 additions & 0 deletions leetcode/0005.Longest-Palindromic-Substring/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 5. Longest Palindromic Substring

<https://leetcode.com/problems/longest-palindromic-substring/>

要找出字串 `s` 中的最長回文
回文的定義是從頭和從尾讀的順序都一樣的字串
(單一個字元也算是回文)

`s` 中可能有不只一組的最長字串,只需要找到其中一組即可

回文根據有或沒有中心點而有兩種形式
例如:`abc|cba`, `bbbcc|ccbbb` 屬於左右對稱型
例如:`abc|e|cba`, `bbbcc|d|ccbbb` 屬於有中心點的類型

要找特定字元的最長迴文,時間複雜度是 $O(n)$
找完所有字元的迴文,時間複雜度是 $O(n^2)$

## Takeaway


0 comments on commit 853d606

Please sign in to comment.