Letter Combinations of a Phone Number,LeetCode
来源:互联网 发布:直接上淘宝网 编辑:程序博客网 时间:2024/05/16 01:42
题目内容就不赘述了,网上看到的方法几乎清一色用到了递归,而我本人不怎么喜(hui)欢递归,略微尝试了一下就放弃了,然后没有用递归同样写出了程序,虽然代码要长一些,复杂一些。
先上代码,已通过。
public List<String> letterCombinations(String digits) {List<String> list = new ArrayList<>();Map<Character, String> map = new HashMap<>();map.put('2', "abc");map.put('3', "def");map.put('4', "ghi");map.put('5', "jkl");map.put('6', "mno");map.put('7', "pqrs");map.put('8', "tuv");map.put('9', "wxyz");String end = "cfilosvz";if("".equals(digits)) {return list;}if(digits.length() == 1) {for(int i = 0;i < map.get(digits.charAt(0)).length();i++) {list.add("" + map.get(digits.charAt(0)).charAt(i));}return list;}char[] c = new char[digits.length()];for(int i = 0;i < digits.length();i++) {c[i] = map.get(digits.charAt(i)).charAt(0);}while(true) {boolean isCompleted = true;String string = "";for (char c1 : c) {string += c1;}list.add(string);for(int i = 0;i < c.length;i++) {if(!end.contains("" + c[i])) {isCompleted = false;break;}}if(isCompleted) {break;}for(int i = c.length - 1;i >= 0;i--) {if(!end.contains("" + c[i])) {c[i] = map.get(digits.charAt(i)).charAt(map.get(digits.charAt(i)).indexOf(c[i] + 1));break;}else {c[i] = map.get(digits.charAt(i)).charAt(0);}}}return list;}
第一步,特殊情况处理,digits为0和1的情况
第二步,把每个数字对应的第一个字符装填到位,下面都以“234”举例,就是将字符数组赋为"adh".
第三步,开始循环。
存"adh"
h是不是4对应字母中的最后一个?不是,那么把h换成i,存"adi"
同上,存"adj"
j是4对应字母中的最后一个,那么j换成4对应的第一个字母h,同时d换成它的下一个字母e,存"aeh"
……
如是循环,加上是否完成遍历的判断,就OK了
P.S
1. 之前本来是打算用栈来解决问题的,没成功,改成这种遍历的方法之后还是用的栈,直到把代码粘贴到这个编辑框,才反应过来,我好像是脑子瓦特了。。。赶紧把栈换成字符数组,不过在写思路的过程中发现其实用字符串应该会更好一些。
2.
String end = "cfilosvz";字符存在于这个字符串 == 字符是对应数字对应的最后一个字母
这个idea解决了7和9有4个字母带来的问题,算是很不错的想法吧
0 0
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- leetcode Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- leetcode: Letter Combinations of a Phone Number
- 多余元素删除之建表算法
- OPENSSL错误码处理
- 非对称加密算法之ElGamal
- 从零构建一个简单的 Python 框架
- 维护库存地点的装运点确认
- Letter Combinations of a Phone Number,LeetCode
- 示例十和示例十二
- 圆周角、圆心角、弦、弦心距、弧长、扇形面积
- 添加Windows用户 本地
- OPENSSL 多次初始化
- 最小生成树 Prime算法 + 时间复杂度
- Android 验证码倒计时功能
- openssl怪现象揭秘
- Lazy Math Instructor