天天看點

leetcode 5(Longest Palindromic Substring)golang實作

  • 思路

    1.因為可能是aba這種奇數的,可能是abba這種偶數的,先統一處理為加“#”分割aba=>#a#b#a# ,abba = #a#b#b#a#這樣可以統一成奇數處理

    2.以每一個字元為開始,向兩邊伸展,(相等繼續,不相等中止)記錄為半徑,半徑最大的就是最長的回文。

func longestPalindrome(s string) string {

   slice := make([]string,,)

   for _ , char := range s {
       slice = append(slice,"#")
       slice = append(slice,string(char))
   }

   slice = append(slice,"#") //先把字元串加上“#”

   maxR :=     //記錄最長的半徑
   maxIndex :=   //記錄最長的 index
   sliceLen := len(slice)

   for index , _ := range slice{

       if(index >=){

           r := 
           i := index - 
           j := index + 

           for {       //每一個字元 計算最長的半徑

               if i< || j >= sliceLen{
                   break
               }

               if(slice[i] == slice[j]){
                   r++
                   i--
                   j++
               }else{
                   break
               }

           }

           if r > maxR{
               maxR = r
               maxIndex = index
           }

       }
   }

   res := ""

   for index,str := range slice{  //maxIndex-maxR到maxIndex+maxR是最長串

       if index >= (maxIndex-maxR) && index <= (maxIndex+maxR) && str != "#"{
           res += str
       } 
   }

   return res

}