码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Letter Combinations of a Phone Number

时间:2016-02-17 12:42:22      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/dick159/p/5194870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!