在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示:
示例 1:
输入: num = "8733", words = ["tree", "used"]
输出: ["tree", "used"]
示例 2:
输入: num = "2", words = ["a", "b", "c", "d"]
输出: ["a", "b", "c"]
提示:
num.length <= 1000
words.length <= 500
words[i].length == num.length
num中不会出现 0, 1 这两个数字
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/t9-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:回溯
Map< Character, List< String> > dict = new HashMap < > ( ) ;
char [ ] chas;
Set< String> set;
List< String> res = new ArrayList < > ( ) ;
public List< String> getValidT9Words ( String num, String[ ] words) {
chas = num. toCharArray ( ) ;
set = new HashSet < > ( Arrays. asList ( words) ) ;
process ( ) ;
return res;
}
public void process ( ) {
dict. put ( '2' , Arrays. asList ( "a" , "b" , "c" ) ) ;
dict. put ( '3' , Arrays. asList ( "d" , "e" , "f" ) ) ;
dict. put ( '4' , Arrays. asList ( "g" , "h" , "i" ) ) ;
dict. put ( '5' , Arrays. asList ( "j" , "k" , "l" ) ) ;
dict. put ( '6' , Arrays. asList ( "m" , "n" , "o" ) ) ;
dict. put ( '7' , Arrays. asList ( "p" , "q" , "r" , "s" ) ) ;
dict. put ( '8' , Arrays. asList ( "t" , "u" , "v" ) ) ;
dict. put ( '9' , Arrays. asList ( "w" , "x" , "y" , "z" ) ) ;
dfs ( new ArrayList < String> ( ) , 0 ) ;
}
private void dfs ( List< String> sub, int idx) {
if ( sub. size ( ) == chas. length) {
StringBuilder sb = new StringBuilder ( ) ;
for ( String s : sub) sb. append ( s) ;
if ( set. contains ( sb. toString ( ) ) ) {
res. add ( sb. toString ( ) ) ;
}
return ;
}
for ( String seed : dict. get ( chas[ idx] ) ) {
sub. add ( seed) ;
dfs ( sub, idx + 1 ) ;
sub. remove ( sub. size ( ) - 1 ) ;
}
}
方法2:映射
public List< String> getValidT9Words ( String num, String[ ] words) {
List< String> res = new ArrayList < > ( ) ;
char [ ] map = { '2' , '2' , '2' , '3' , '3' , '3' , '4' , '4' , '4' , '5' , '5' , '5' , '6' , '6' , '6' , '7' , '7' , '7' , '7' , '8' , '8' , '8' , '9' , '9' , '9' , '9' } ;
for ( String word : words) {
int index = 0 ;
boolean flag = true ;
for ( char c : word. toCharArray ( ) ) {
char n = map[ c - 'a' ] ;
if ( n != num. charAt ( index++ ) ) {
flag = false ;
break ;
}
}
if ( flag) res. add ( word) ;
}
return res;
}