[LeetCode-interview algorithm classic-Java implementation] [017-Letter Combinations of a Phone Number (word Combinations on Phone numbers)], Chapter 9 leetcode
[017-Letter Combinations of a Phone Number (a word combination on the Phone Number )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a digit string, return all possible letter combinations that the number coshould 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"].
Note:Although the above answer is in lexicographical order, your answer cocould be in any order you want.
Theme
If a number string is specified, all combinations of All characters in the number are returned. The ing between numbers and characters is shown in.
Note:Although the above results are arranged in character order, you can return results in any order.
Solutions
Use an array to save the ing between numbers and words. Based on the input of the number string, find the corresponding characters and combine the results.
Code Implementation
Public class Solution {private String [] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv ", "wxyz" ,}; private List <String> result; // store the final result private char [] chars; // Save the result of removing characters: private char [] curResult; // store the intermediate result private int end = 0; // The first unused position in the character array private int handle = 0; // The number of characters currently being processed is public List <String> letterCombinations (String digits) {result = new shortlist <> (); if (digits! = Null & digits. length ()> 0) {chars = digits. toCharArray (); // process the string, remove 0 and 1 // find the first 0 or 1 position while (end <digits. length () & chars [end]! = '0' & chars [end]! = '1') {end ++;} handle = end + 1; while (handle <chars. length) {if (chars [handle]! = '0' & chars [handle]! = '1') {chars [end] = chars [handle]; end ++;} handle ++;} curResult = new char [end]; // After while, end is the length of valid characters handle = 0; // point to the first valid character location letterCombinations ();} return result;} private void letterCombinations () {if (handle> = end) {result. add (new String (curResult);} else {int num = chars [handle]-'2'; for (int I = 0; I <map [num]. length (); I ++) {curResult [handle] = map [num]. charAt (I); handle ++; letterCombinations (); handle --;}}}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/46980259]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.