LeetCode 17?電話號碼的字母組合
先貼代碼
class Solution {
List<String> result = new ArrayList<>();
String temp = new String("");
Integer num;
public List<String> letterCombinations(String digits) {
dfs(digits, 0);
return result;
}
public void dfs(String digits, int deepfloor) {
if(digits.compareTo("") == 0) {
return;
}
if(deepfloor == digits.length()) {
result.add(new String(temp));
return;
}
num = Integer.valueOf(digits.substring(deepfloor,deepfloor+1));
// num = Integer.valueOf(digits.charAt(deepfloor)); 這是錯誤寫法
String sub = numberToString(num);
for(int j=0;j<sub.length();j++) {
temp = temp + sub.substring(j,j+1);
dfs(digits, deepfloor+1);
temp = temp.substring(0, deepfloor);
}
}
public String numberToString(int num) {
switch(num)
{
case 2:
return "abc";
case 3:
return "def";
case 4:
return "ghi";
case 5:
return "jkl";
case 6:
return "mno";
case 7:
return "pqrs";
case 8:
return "tuv";
case 9:
return "wxyz";
}
return "";
}
}
踩坑:
1、假設(shè)digits = "23",deepfloor = 0。
如果num = ?Integer.valueOf(digits.charAt(deepfloor));?
num=50,這是為什么呢,因為digits.charAt(deepfloor)='2',對應(yīng)的ASCII值為50...
而?num = ?Integer.valueOf(digits.substring(deepfloor,deepfloor+1));
num=2,才能得到正確結(jié)果,因為digits.substring(deepfloor,deepfloor+1)="2",Integer.valueOf()方法只能用于字符串,例如"2",而不能用于單個字符,例如'2'。
2、String temp =? new String("");
是否""字符串會占據(jù)一個字符位置呢?
分別測試了當(dāng)字符串temp為""的第0位字符
和拼接字符串"A"之后temp的第0位字符
首先當(dāng)temp為""時, 測試System.out.println(temp.charAt(0));
會報錯java.lang.StringIndexOutOfBoundsException: String index out of range: 0
因此,""其實不占據(jù)字符位
當(dāng)temp拼接字符串"A"之后, 測試System.out.println(temp.charAt(0));
順利輸出字符'A'
因此也不用擔(dān)心,通過拼接字符串,初始化"",會造成索引錯亂的情況
但是,更好的辦法應(yīng)該是使用StringBuilder
如果是純字符串拼接,會生成很多臨時對象,性能會略差,Java實現(xiàn)中是用StringBuilder做拼接的。文章來源:http://www.zghlxwxcb.cn/news/detail-732319.html
StringBuilder留到下一次實現(xiàn)。文章來源地址http://www.zghlxwxcb.cn/news/detail-732319.html
class Solution {
List<String> result = new ArrayList<>();
String temp = new String("");
public List<String> letterCombinations(String digits) {
System.out.println(temp.charAt(0));
temp = temp + "A";
System.out.println(temp.charAt(0));
return result;
}
}
到了這里,關(guān)于Integer.valueOf()用于字符和字符串的區(qū)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!