https://leetcode.com/problems/letter-combinations-of-a-phone-number/
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.
This is problem is easy except the use of HashMap.
Java has three kinds of Hashtalbe implementations. They are HashTable
, HashMap
, HashSet
. HashTable
is a thread safe implementation, but it is not efficient. For a single thread problem, we always use HashMap
.
HashMap
have several important methods. They are put(key, value)
, get(key)
, keySet()
, values()
.
put(key value)
will insert the pair key-value into hashtable. For example:
Map<String,String> map = new HashMap<String,String>();
map.put("one","xiaoming"); // it doesn't have add method since
map.put("two","xiaozhang"); // it does not implement Collection
map.put("three","xiaoli"); // interface
map.put("four","xiaoliu");
one
, two
, three
, four
are keys and xiaoming
, xiaozhang
, xiaoli
, xiaoliu
are values.
get(key)
get(key)
will return value which combines with key. For example:
System.out.println(map.get("one"));
System.out.println(map.get("two"));
System.out.println(map.get("three"));
System.out.println(map.get("four"));
The output will be:
xiaoming
xiaozhang
xiaoli
xiaoliu
keySet()
keySet()
will return all keys stored in hashtable.
System.out.println(map.keySet());
The output is:
[four, one, two, three]
values()
values()
will return all values stored in hashtable.
System.out.println(map.value());
The output is:
[xiaolu, xiaoming, xiaozhang, xiaoli]
Solution
1 |
|
近期评论