A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1'B' -> 2...'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message"12"
, it could be decoded as "AB"
(1 2) or "L"
(12). The number of ways decoding "12"
is 2.
规律题,总结规律即可:
package mainimport ( "fmt" "strconv")//只需要判断双位数的情况func is_suit_num(num int) bool { if num >= 10 && num <= 26 { return true } else { return false }}func char_style_num(char string) int { length := len(char) if length < 2 { return 1 } num := char[0:2] num_int, _ := strconv.Atoi(num) if is_suit_num(num_int) { return char_style_num(char[1:]) + char_style_num(char[2:]) } else { return char_style_num(char[1:]) }}func main() { fmt.Printf("%d\n", char_style_num("12")) //1,2;12 = 2 fmt.Printf("%d\n", char_style_num("122")) //1,2,2; //12,2; //1,22; = 3 fmt.Printf("%d\n", char_style_num("1221")) //1,2,2,1; //12,2,1; //12,21; //1,22,1; //1,2,21; = 5 fmt.Printf("%d\n", char_style_num("3121")) //3,1,2,1; //3,12,1; //3,1,21; = 3 //-------------------- 总结出规律 ---------------------- // // if arr[N:N-1] suit // F(N) = F(N-1) + F(N-2) // else // F(N) = F(N-1)}
程序输出结果:
2 3 5 3