LeetCode Letter Combinations of a Phone Number

来源:互联网 发布:学知不足 教然后知困 编辑:程序博客网 时间:2024/06/05 15:19

Description:

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.

Solution:

We can use a dfs to solve this problem.

For every digit, we try to map it with the character in the map, and use this as the dfs condition. When it comes to the index/token is equal to the length of whole length, which means it runs into the end, then we can stop the dfs, and add the current string to the LinkedList.

import java.util.LinkedList;public class Solution {public LinkedList<String> letterCombinations(String digits) {LinkedList<String> list = new LinkedList<String>();if (digits.equals(""))return list;dfs(list, 0, digits, "");return list;}void dfs(LinkedList<String> list, int tot, String digits, String current) {if (tot == digits.length()) {list.add(current);return;} else {char ch = digits.charAt(tot);char arr[] = match(ch);for (int i = 0; i < arr.length; i++) {dfs(list, tot + 1, digits, current + arr[i]);}}}char[] match(char ch) {char[] ret = null;switch (ch) {case '2':return new char[] { 'a', 'b', 'c' };case '3':return new char[] { 'd', 'e', 'f' };case '4':return new char[] { 'g', 'h', 'i' };case '5':return new char[] { 'j', 'k', 'l' };case '6':return new char[] { 'm', 'n', 'o' };case '7':return new char[] { 'p', 'q', 'r', 's' };case '8':return new char[] { 't', 'u', 'v' };case '9':return new char[] { 'w', 'x', 'y', 'z' };case '*':return new char[] { '+' };case '0':return new char[] { ' ' };}return ret;}}


0 0