【LeetCode-面試演算法經典-Java實現】【017-Letter Combinations of a Phone Number (電話號碼上的單片語合)】,九章演算法leetcode
【017-Letter Combinations of a Phone Number (電話號碼上的單片語合)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
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"].
Note: Although the above answer is in lexicographical order, your answer could be in any order you want.
題目大意
給定一個數字串,返回數字上所有字元的所有組合,數字到字元的映射如所示。
注意: 儘管上面的結果以字元順序排列的,你可以以任何順序返回結果。
解題思路
用一個數組儲存數字和字的映射關係,根據數字串的輸入,找到對應的字元,組合結果。
代碼實現
public class Solution { private String[] map = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", }; private List<String> result; // 儲存最終結果 private char[] chars; // 儲存去掉0,1字元的結果 private char[] curResult; // 儲存中間結果 private int end = 0; // 字元數組中的第一個未使用的位置 private int handle = 0; // 當前處理的是第幾個字元數字 public List<String> letterCombinations(String digits) { result = new LinkedList<>(); if (digits != null && digits.length() > 0) { chars = digits.toCharArray(); // 對字串進行處理,去掉0和1 // 找第一個0或者1的位置 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]; // while結束後,end為有效字元的長度 handle = 0; // 指向第一個有效字元的位置 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--; } } }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/46980259】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。