91.go 747 B

12345678910111213141516171819202122232425262728293031323334
  1. package main
  2. func numDecodings(s string) int {
  3. // just like the stair jumping problem,
  4. // solution cnt = last cnt + last last cnt (under some condition)
  5. strLen := len(s)
  6. if strLen == 0 || s[0] == '0' {
  7. return 0
  8. } else if strLen == 1 {
  9. return 1
  10. }
  11. solutionCnt := make([]int, strLen)
  12. solutionCnt[0] = 1
  13. if s[0] == '1' || (s[0] == '2' && s[1] <= '6') {
  14. solutionCnt[1] = 1
  15. }
  16. if s[1] != '0' {
  17. solutionCnt[1] += solutionCnt[0]
  18. }
  19. for i := 2; i < strLen; i++ {
  20. if s[i-1] == '1' || (s[i-1] == '2' && s[i] <= '6') {
  21. solutionCnt[i] += solutionCnt[i-2]
  22. }
  23. if s[i] != '0' {
  24. solutionCnt[i] += solutionCnt[i-1]
  25. }
  26. }
  27. return solutionCnt[strLen-1]
  28. }
  29. // func main() {
  30. // str := "12345120"
  31. // fmt.Println(numDecodings(str))
  32. // }