当前位置:网站首页>【Hot100】17. 电话号码的字母组合
【Hot100】17. 电话号码的字母组合
2022-07-01 15:49:00 【王六六的IT日常】
- 回溯
在循环里面套了递归调用
代码实现时有个小细节,如果是纯字符串拼接,会生成很多临时对象,性能会略差,Java实现中是用StringBuilder做拼接的,经测试耗时0毫秒,如果是用String类型做拼接耗时是6毫秒。
class Solution {
//一个映射表,第二个位置是"abc“,第三个位置是"def"。。。
//这里也可以用map,用数组可以更节省点内存
String[] letter_map = {
" ","*","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
//注意边界条件
if(digits==null || digits.length()==0) {
return new ArrayList<>();
}
iterStr(digits, new StringBuilder(), 0);
return res;
}
//最终输出结果的list
List<String> res = new ArrayList<>();
//递归函数
void iterStr(String str, StringBuilder letter, int index) {
//递归的终止条件,注意这里的终止条件看上去跟动态演示图有些不同,主要是做了点优化
//动态图中是每次截取字符串的一部分,"234",变成"23",再变成"3",最后变成"",这样性能不佳
//而用index记录每次遍历到字符串的位置,这样性能更好
if(index == str.length()) {
res.add(letter.toString());
return;
}
//获取index位置的字符,假设输入的字符是"234"
//第一次递归时index为0所以c=2,第二次index为1所以c=3,第三次c=4
//subString每次都会生成新的字符串,而index则是取当前的一个字符,所以效率更高一点
char c = str.charAt(index);
//map_string的下表是从0开始一直到9, c-'0'就可以取到相对的数组下标位置
//比如c=2时候,2-'0',获取下标为2,letter_map[2]就是"abc"
int pos = c - '0';
String map_string = letter_map[pos];
//遍历字符串,比如第一次得到的是2,页就是遍历"abc"
for(int i=0;i<map_string.length();i++) {
//调用下一层递归,用文字很难描述,请配合动态图理解
letter.append(map_string.charAt(i));
//如果是String类型做拼接效率会比较低
//iterStr(str, letter+map_string.charAt(i), index+1);
iterStr(str, letter, index+1);
letter.deleteCharAt(letter.length()-1);
}
}
}
- 队列
可以利用队列的先进先出特点,再配合循环
class Solution {
public List<String> letterCombinations(String digits) {
if(digits==null || digits.length()==0) {
return new ArrayList<String>();
}
//一个映射表,第二个位置是"abc“,第三个位置是"def"。。。
//这里也可以用map,用数组可以更节省点内存
String[] letter_map = {
" ","*","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"
};
List<String> res = new ArrayList<>();
//先往队列中加入一个空字符
res.add("");
for(int i=0;i<digits.length();i++) {
//由当前遍历到的字符,取字典表中查找对应的字符串
String letters = letter_map[digits.charAt(i)-'0'];
int size = res.size();
//计算出队列长度后,将队列中的每个元素挨个拿出来
for(int j=0;j<size;j++) {
//每次都从队列中拿出第一个元素
String tmp = res.remove(0);
//然后跟"def"这样的字符串拼接,并再次放到队列中
for(int k=0;k<letters.length();k++) {
res.add(tmp+letters.charAt(k));
}
}
}
return res;
}
}
边栏推荐
- MySQL advanced 4
- ABAP-调用Restful API
- Embedded development: five revision control best practices
- 软件测试的可持续发展,必须要学会敲代码?
- Summer Challenge harmonyos canvas realize clock
- Where should older test / development programmers go? Will it be abandoned by the times?
- How does win11 set user permissions? Win11 method of setting user permissions
- [300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)
- Équipe tensflow: Nous ne sommes pas abandonnés
- 6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
猜你喜欢
![[200 opencv routines] 216 Draw polylines and polygons](/img/47/3e5564ff9cf5fa3ef98a2ea27694cf.png)
[200 opencv routines] 216 Draw polylines and polygons

大龄测试/开发程序员该何去何从?是否会被时代抛弃?

Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)

使用腾讯云搭建图床服务
![[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)](/img/cf/44b3983dd5d5f7b92d90d918215908.png)
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)

Share the daily work and welfare of DJI (Shenzhen headquarters) in Dajiang

超视频时代,什么样的技术会成为底座?

Pico,是要拯救还是带偏消费级VR?
![[STM32 learning] w25qxx automatic judgment capacity detection based on STM32 USB storage device](/img/41/be7a295d869727e16528041ad08cd4.png)
[STM32 learning] w25qxx automatic judgment capacity detection based on STM32 USB storage device

Where should older test / development programmers go? Will it be abandoned by the times?
随机推荐
硬件开发笔记(九): 硬件开发基本流程,制作一个USB转RS232的模块(八):创建asm1117-3.3V封装库并关联原理图元器件
When ABAP screen switching, refresh the previous screen
Pico,能否拯救消费级VR?
u本位合约和币本位合约有区别,u本位合约会爆仓吗
嵌入式开发:5个修订控制最佳实践
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)
[video memory optimization] deep learning video memory optimization method
Does 1.5.1 in Seata support mysql8?
二叉树的前序,中序,后续(非递归版本)
There will be a gap bug when the search box and button are zoomed
Go语学习笔记 - gorm使用 - 表增删改查 | Web框架Gin(八)
Tanabata confession introduction: teach you to use your own profession to say love words, the success rate is 100%, I can only help you here ~ (programmer Series)
There is a difference between u-standard contract and currency standard contract. Will u-standard contract explode
使用腾讯云搭建图床服务
The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
Pocket network supports moonbeam and Moonriver RPC layers
ADS算力芯片的多模型架构研究
Microservice tracking SQL (support Gorm query tracking under isto control)
ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
[每日一氵]Latex 的通讯作者怎么搞
