java实现英文输入法单词联想功能
前言
主管期望你来实现英文输入法单词联想功能
需求如下:
依据用户输入的单词前缀,从已输入的英文语句中联想出用户想输入的单词,按字典序输出联想到的单词序列如果联想不到,请输出用户输入的单词前缀。
注意:
1.英文单词联想时,区分大小写
2.缩略形式如"don’t”,判定为两个单词,"don”和”t
3.输出的单词序列,不能有重复单词,且只能是英文单词,不能有标点符号。
输入描述:
输入为两行,首行输入一段由英文单词word和标点符号组成的语句str,接下来一行为一个英文单词前缀pre.
0< word.length()<= 20
0<str.length <= 10000
0< pre <= 20
输出描述:
输出符合要求的单词序列或单词前缀,存在多个时,单词之间以单个空格分割
用例:
输入:
The furthest distance in the world, ls not between life and death, But when l stand in front of you, Yet you don’t know that I love you.
t
输出:the t that
java代码实现(开箱即用)
package com.des.data.test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class EnglishInputMethod {
public static void main(String[] args) {
String str1 = "The furthest distance in the world, ls not between life and death, But when l stand in front of you, Yet you don't know that I love you.";
String str2 = "t";
System.out.println(solution(str1, str2));
}
public static String solution(String str1, String pre) {
StringBuffer resb = new StringBuffer();
StringBuffer lb = new StringBuffer();
//去除标点符号
for (int i = 0; i < str1.length(); i++) {
char c = str1.charAt(i);
if (!(Character.isLowerCase(c) || Character.isUpperCase(c))) {
lb.append(" ");
continue;
}
lb.append(c);
}
String[] strs = lb.toString().split(" ");
List<String> resList = Arrays.asList(strs).stream().filter(p -> p.startsWith(pre)).collect(Collectors.toList());
if (resList.isEmpty()) {
return pre;
}
for (int i = 0; i < resList.size(); i++) {
resb.append(resList.get(i)).append(" ");
}
return resb.toString();
}
}