|
@@ -0,0 +1,64 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var s string
|
|
|
+
|
|
|
+ s = "a"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "ab"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "aba"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "abab"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "ababc"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "babad"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+
|
|
|
+ s = "cbbd"
|
|
|
+ fmt.Println(longestPalindrome(s))
|
|
|
+}
|
|
|
+
|
|
|
+// 双指针法
|
|
|
+func longestPalindrome(s string) string {
|
|
|
+ var palindromeStr string
|
|
|
+ var cursorFront, cursorBack int
|
|
|
+ for i := 0; i < len(s); i++ {
|
|
|
+ cursorFront = i
|
|
|
+ for j := len(s) - 1; j >= i; j-- {
|
|
|
+ cursorBack = j
|
|
|
+ if s[cursorFront] != s[cursorBack] {
|
|
|
+ cursorBack--
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ isPalindrome := checkString(cursorFront, cursorBack, s)
|
|
|
+ if !isPalindrome {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ if cursorBack-cursorFront+1 > len(palindromeStr) {
|
|
|
+ palindromeStr = s[cursorFront : cursorBack+1]
|
|
|
+ break
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return palindromeStr
|
|
|
+}
|
|
|
+
|
|
|
+func checkString(min, max int, s string) bool {
|
|
|
+ for min <= max {
|
|
|
+ if s[min] != s[max] {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ min++
|
|
|
+ max--
|
|
|
+ }
|
|
|
+ return true
|
|
|
+}
|