LeetCode Letter Combinations of a Phone Number

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值