c++ 解答版本
class Solution {
public:
vector<string> letterCombinations(string digits) {
map<char,vector<char>> k = {
{'2', {'a', 'b', 'c'}},
{'3', {'d', 'e', 'f'}},
{'4', {'g', 'h', 'i'}},
{'5', {'j', 'k', 'l'}},
{'6', {'m', 'n', 'o'}},
{'7', {'p', 'q', 'r', 's'}},
{'8', {'t', 'u', 'v'}},
{'9', {'w', 'x', 'y', 'z'}}
};
vector<string> res;
if (digits==""){
return res;
}
res = {""};
for (char x:digits){
vector<string> temp;
for (string z:res){
for (char y:k[x]){
temp.push_back(z+y);
}
}
res = temp;
}
return res;
}
};
注意點(diǎn):
- map 構(gòu)造,{{key,value},{key,value}}
- string 類型 + char 類型 可行
go 解答版本
func letterCombinations(digits string) []string {
k := map[byte][]byte{
'2': {'a', 'b', 'c'},
'3': {'d', 'e', 'f'},
'4': {'g', 'h', 'i'},
'5': {'j', 'k', 'l'},
'6': {'m', 'n', 'o'},
'7': {'p', 'q', 'r', 's'},
'8': {'t', 'u', 'v'},
'9': {'w', 'x', 'y', 'z'},
}
res := []string{""}
if digits==""{
return []string{}
}
for _,v := range digits{
var temp []string
for _,pre := range res{
for _,cur := range k[byte(v)]{
temp=append(temp,pre+string(cur))
}
}
res = temp
}
return res
}
注意點(diǎn):
兩種初始化方式,
var temp []string,res := []string{""}類型轉(zhuǎn)換,
''單引號代表 byte,golang 中沒有 char 類型,它的字符類型被稱為 rune 類型。rune 類型是一種整數(shù)類型,而不是 ASCII 碼或 Unicode 字符的字符類型,它可以存儲單個(gè)字符,并使用 UTF-8 編碼進(jìn)行表示。因此,在 Go 代碼中,通常使用 byte 或 rune 來處理單個(gè)字符。其中,byte 類型最適合處理 ASCII 碼字符,而 rune 類型則更適用于字符串和 Unicode 字符。如果需要將字符轉(zhuǎn)換為字符串,則可以使用 string() 函數(shù)將 rune 轉(zhuǎn)換為字符串。
rune 與 byte 的區(qū)別以及如何選擇:
byte 和 rune 都是基本數(shù)據(jù)類型,它們的主要區(qū)別在于所表示的數(shù)據(jù)范圍和相應(yīng)的長度。
一般而言,byte 類型用來表示字節(jié)值,取值范圍為 0~255,長度為1個(gè)字節(jié);而 rune 類型用來表示一個(gè) Unicode 碼點(diǎn)(Unicode Code Point),即可以表示任何一個(gè) Unicode 字符,取值范圍為 0 到 0x10FFFF,長度為 4 個(gè)字節(jié)。而且,byte 類型相當(dāng)于 uint8 類型的別名,而 rune 類型相當(dāng)于 int32 類型的別名。
在字符串操作方面,Go 語言中 string 類型底層實(shí)際上是以 byte 序列的結(jié)構(gòu)存儲的,并且支持使用索引訪問其中的字節(jié)。因此,如果要直接處理 ASCII 編碼的字符或者二進(jìn)制數(shù)據(jù),則可以使用 byte 類型;而如果需要處理 Unicode 編碼的字符,則應(yīng)該使用 rune 類型。