Skip to content

dynamic programming message decoding #1

@phamvancam2104

Description

@phamvancam2104

I think the best way to solve such a problem is to use dynamic programming.

Assume a[1..l] is the array of numbers in the encoded message, assume the first n-1 numbers in the encoded message can be decoded into f(n-1) messages.
Then, we have f(n) = f(n-1) + f(n-2) if the a[n]a[n-1] are a valid encoded character, otherwise f(n) = f(n-1)
The following is my attempt to solve it with a linear complexity.

`func countDecodes(message string) int {
l := len(message)
a, b := 1, 1
for i := 2; i < l+1; i++ {
temp := a
a = b
w := string(message[i-2]) + string(message[i-1])
countLminus2 := 0
if isCorrectWord(w) {
countLminus2 = temp
}
b = b + countLminus2
}
return b
}

func isCorrectWord(w string) bool {
val, err := strconv.Atoi(w)
if err != nil || val < 1 || val > 26 {
return false
}

return true

}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions