Longest Palindrome go语言实现

2018-09-22  本文已影响0人  fjxCode

Longest Palindrome

题目描述

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

原串是回文的思路(理解错题了):

解:

//原串是回文的写法
func longestPalindrome(s string) int {
    sSlice := []rune(s)
    dp := make([][]bool,len(s),len(s))
    maxLen := 0
    for idx,_ := range dp{
        dp[idx] = make([]bool,len(s),len(s))
    }
    for i:=0;i<len(sSlice);i++{
        dp[i][i] = true
        maxLen = 1
    }
    if len(sSlice)>1{
        for i:=0;i<len(sSlice)-1;i++{
            if sSlice[i] == sSlice[i+1] {
                dp[i][i+1] = true
                maxLen = 2
            }
        }
    }
    if len(sSlice) >= 3{
        for i:=len(sSlice)-3;i>=0;i--{
            for j:=i+2;j< len(sSlice) ;j++ {
                if sSlice[i] == sSlice[j] && dp[i+1][j-1] == true{
                    dp[i][j] = true
                    if j-i+1 > maxLen  {
                        maxLen = j-i+1
                    }
                }
            }
        }
    }
    return maxLen
}

可构成回文串的思路(原题意):

解:

func longestPalindrome(s string) int {
    sSlice := []rune(s)
    count := make([]int,128)
    for _,elem := range sSlice{
        count[elem]++
    }
    res := 0
    for _,elem := range count{
        res += elem/2*2
        if res%2 == 0 && elem%2 == 1{
            res++
        }
    }
    return res
}
上一篇 下一篇

猜你喜欢

热点阅读