[LeetCode]Letter Combinations of a Phone Number
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
额,比较水,随便搞搞就好了。递归一下,这里就预处理了数字对应的字符串。
Code
package leetcode.LetterCombinationsofaPhoneNumber; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Solution { private String[] maps = new String[ 10 ]; private void make() { maps[ 2 ] = new String( "abc" ); maps[ 3 ] = new String( "def" ); maps[ 4 ] = new String( "ghi" ); maps[ 5 ] = new String( "jkl" ); maps[ 6 ] = new String( "mno" ); maps[ 7 ] = new String( "pqrs" ); maps[ 8 ] = new String( "tuv" ); maps[ 9 ] = new String( "wxyz" ); } public List<String> letterCombinations( String digits ) { make(); List<String> ret = new ArrayList<String>(); if( digits.length() < 1 ) return ret; go( ret, digits, "", 0 ); return ret; } private void go( List<String> ret, String digits, String str, int pos ) { if( pos == digits.length() - 1 ) { String s = maps[ digits.charAt( pos ) - ‘0‘ ]; for( int i = 0; i < s.length(); i++ ) { ret.add( str + s.charAt( i ) ); } } else { String s = maps[ digits.charAt( pos ) - ‘0‘ ]; for( int i = 0; i < s.length(); i++ ) { go( ret, digits, str + s.charAt( i ) + "", pos + 1 ); } } } public static void main( String[] args ) { // TODO Auto-generated method stub Solution s = new Solution(); String digits = "234"; for( String str : s.letterCombinations( digits ) ) { System.out.println( str ); } } }
以上是关于[LeetCode]Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章
leetcode1079. Letter Tile Possibilities
[LeetCode] 1079. Letter Tile Possibilities
[LeetCode]Letter Combinations of a Phone Number
Leetcode 17. Letter Combinations of a Phone Number
LeetCode算法题python解法:17. Letter Combinations of a Phone Number