当前位置:网站首页>【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;
}
}
边栏推荐
- How to adjust the color of the computer screen and how to change the color of the computer screen
- Programming examples of stm32f1 and stm32subeide - production melody of PWM driven buzzer
- July 1, 2022 Daily: Google's new research: Minerva, using language models to solve quantitative reasoning problems
- Advanced cross platform application development (24): uni app realizes file download and saving
- Comment win11 définit - il les permissions de l'utilisateur? Win11 comment définir les permissions de l'utilisateur
- Embedded development: five revision control best practices
- u本位合约和币本位合约有区别,u本位合约会爆仓吗
- 近半年内连获5家“巨头”投资,这家智能驾驶“黑马”受资本追捧
- Overview | slam of laser and vision fusion
- 表格存储中tablestore 目前支持mysql哪些函数呢?
猜你喜欢

ATSs: automatically select samples to eliminate the difference between anchor based and anchor free object detection methods

电脑照片尺寸如何调整成自己想要的

MySQL的零拷贝技术

工厂高精度定位管理系统,数字化安全生产管理

MySQL backup and restore single database and single table
![[one day learning awk] function and user-defined function](/img/e1/a378211ef05fcc4d469363f3e509a7.png)
[one day learning awk] function and user-defined function

使用腾讯云搭建图床服务

揭秘慕思“智商税”:狂砸40亿搞营销,发明专利仅7项

【OpenCV 例程200篇】216. 绘制多段线和多边形
![[one day learning awk] conditions and cycles](/img/e6/c96a4fd6ced9b492e70a06004f5159.png)
[one day learning awk] conditions and cycles
随机推荐
process. env. NODE_ ENV
Pnas: brain and behavior changes of social anxiety patients with empathic embarrassment
Zhang Chi Consulting: lead lithium battery into six sigma consulting to reduce battery capacity attenuation
Zhang Chi Consulting: household appliance enterprises use Six Sigma projects to reduce customers' unreasonable return cases
[PHP graduation design] design and implementation of textbook management system based on php+mysql+apache (graduation thesis + program source code) -- textbook management system
[200 opencv routines] 216 Draw polylines and polygons
【显存优化】深度学习显存优化方法
RT-Thread Env 工具介绍(学习笔记)
自动、智能、可视!深信服SSLO方案背后的八大设计
Pico,能否拯救消费级VR?
Crypto Daily:孙宇晨在MC12上倡议用数字化技术解决全球问题
ABAP call restful API
Microservice tracking SQL (support Gorm query tracking under isto control)
Pico,是要拯救还是带偏消费级VR?
[STM32 learning] w25qxx automatic judgment capacity detection based on STM32 USB storage device
一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...
Day 3 of rhcsa study
#夏日挑战赛# HarmonyOS canvas实现时钟
The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
u本位合约和币本位合约有区别,u本位合约会爆仓吗
