Longest Palindromic Subsequence

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

Longest Palindromic Subsequence

题目描述

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

Example 1:
Input:

"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:

"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".

思路:

解:

package main

import "fmt"

func longestPalindromeSubseq(s string) int {
    sSlice := []rune(s)
    dp := make([][]int,len(sSlice)+1)
    for idx,_ := range dp{
        dp[idx] = make([]int,len(sSlice))
    }
    for i:= 0;i< len(sSlice);i++{
        dp[1][i] = 1
    }

    for i := 2; i<len(sSlice)+1;i++  {
        for j := 0; j<(len(sSlice)-i+1);j++  {
            if sSlice[j]== sSlice[i+j-1] {
                dp[i][j] = dp[i-2][j+1]+2
            }else {
                switch dp[i-1][j] > dp[i-1][j+1] {
                case true:
                    dp[i][j] = dp[i-1][j]
                case false:
                    dp[i][j] = dp[i-1][j+1]
                }
            }
        }
    }
    fmt.Println(dp)
    return dp[len(sSlice)][0]
}

func main()  {
    s := "bbbab"
    res := longestPalindromeSubseq(s)
    fmt.Print(res)
}
上一篇 下一篇

猜你喜欢

热点阅读