一條包含字母 a-z 的訊息通過以下方式進行了編碼:
『a』 -> 1
『b』 -> 2
…『z』 -> 26
給定乙個只包含數字的非空字串,請計算解碼方法的總數。
示例 1:
輸入: 「12」
輸出: 2
解釋: 它可以解碼為 「ab」(1 2)或者 「l」(12)。
示例 2:
輸入: 「226」
輸出: 3
解釋: 它可以解碼為 「bz」 (2 26), 「vf」 (22 6), 或者 「bbf」 (2 2 6) 。
private
static
final map
dictionary =
newhashmap
<
>()
;private
int res =0;
static
}//解法1 回溯法 (超時)
public
intnumdecodings
(string s)
//從s的第index位置開始解碼
private
void
numdecodings
(string s,
int index)
for(
int i =
1; i <=
2&& index + i <= s.
length()
; i++)}
}//解法2 遞迴法 (超時)
public
intnumdecodings2
(string s)
if(s.
length()
==1) string temp = s.
substring(0
,2);
if(dictionary.
containskey
(temp)
)else
return
numdecodings2
(s.substring(1
));}
}//解法3 記憶搜尋法
public
intnumdecodings3
(string s)
private
intnumdecodings3
(string s, map
map)
if(s.
length()
==1)if
(!map.
containskey
(s))
else
else}}
return map.
get(s);}
//解法4 動態規劃
public
intnumdecodings4
(string s)
else
}int n = s.
length()
;//mem[i]表示s的第i個位置到最後表示的字串可以解碼的方法總數
int[
] mem =
newint
[n +1]
;if(s.charat
(n-1)==
'0')
else
if(s.
charat
(n -2)
=='0'
)else
else
}for
(int i = n -
3; i >=
0; i--
)else
else}}
return mem[1]
;}public
static
void
main
(string args)
LeetCode91 解碼方法
這題,我花了好大的功夫才通過,中途踩了很多坑,從這個15頂25踩,通過率只有10 多,就能看出這個題,雖然是乙個中等難度的題,但是並沒有那麼好做。看到題目,感覺有點像爬樓梯的那個?想到用動態規劃。第一次寫 沒有考慮0的情況,出錯,那麼就考慮吧,如果出現在頭,就返回0,出現的中間的話。不過我是從後往前...
LeetCode 91 解碼方法
一條包含字母a z的訊息通過以下方式進行了編碼 a 1 b 2 z 26 給定乙個只包含數字的非空字串,請計算解碼方法的總數。示例 1 輸入 12 輸出 2 解釋 它可以解碼為 ab 1 2 或者 l 12 示例 2 輸入 226 輸出 3 解釋 它可以解碼為 bz 2 26 vf 22 6 或者 ...
leetcode 91 解碼方法
一條包含字母a z的訊息通過以下方式進行了編碼 a 1 b 2 z 26給定乙個只包含數字的非空字串,請計算解碼方法的總數。示例 1 輸入 12 輸出 2解釋 它可以解碼為 ab 1 2 或者 l 12 示例 2 輸入 226 輸出 3解釋 它可以解碼為 bz 2 26 vf 22 6 或者 bbf...