phonebook

revised version:

 

package algorithm.weixin;

public class PhoneBook
{
    // static array initialization
    public static final char[][] PHONEKEY = {
                {'0', '0', '0'},
                {'1', '1', '1'},
                {'a', 'b', 'c'},
                {'d', 'e', 'f'},
                {'g', 'h', 'i'},
                {'j', 'k', 'l'},
                {'m', 'n', 'o'},
                {'p', 'r', 's'},
                {'t', 'u', 'v'},
                {'w', 'x', 'y' }
                };
    private static final int KEYCHARS = 3;
    public static void printPhoneNumbers( int number )
    {
        if( number > Integer.MAX_VALUE )
        {
            System.out.println( "input is invalid" );
        }
        StringBuilder sb = new StringBuilder( Integer.toString( number ) );
//        StringBuilder result = new StringBuilder( );
        char[] tempResult = new char[10];
        printCombinations( sb, tempResult, 0 );
    }
    public static void printCombinations( StringBuilder sb, char[] tempResult, int start )
    {
        if( start <= sb.length( ) - 1 )
        {
            char temp = sb.charAt( start );
            for( int i = 0; i < KEYCHARS; i++ )
            {
                String s = Character.toString(temp);
                int num = Integer.parseInt( s );
                tempResult[start] =  PHONEKEY[num][i] ;
                printCombinations( sb, tempResult, start + 1 );
            }
        }   
        if( start == sb.length( ))
        {
            printCharArray( tempResult );
            return;
        }
    }
    public static void printCharArray( char[] arr )
    {
        for( int i =0; i < arr.length; i++ )
        {
            System.out.print( arr[i] + " " );
        }
        System.out.println( "===" );
    }

    /**
     * @param args
     */
    public static void main( String[] args )
    {
        printPhoneNumbers( 517583456 );

    }

}

Advertisements
This entry was posted in interview and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s