[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 );
        }
    }
}    

 





posted @ 2016-02-17 11:51  hudiwei-hdw  阅读(133)  评论(0编辑  收藏  举报