主管期望你来实现英文输入法单词联想功能,需求如下:
注意
输入两行
首行输入一段由英文单词word
和标点
构成的语句str
接下来一行为一个英文单词前缀pre
0 < word.length() <= 20
0 < str.length() <= 10000
0 < pre.length() <= 20
输出符合要求的单词序列或单词前缀
存在多个时,单词之间以单个空格分割
I love you
He
He
用户已输入单词语句"I love you"
,
中提炼出"I"
,"love"
,"you"
三个单词
接下来用户输入"He"
,
从已经输入信息中无法联想到符合要求的单词
所以输出用户输入的单词前缀
The furthest distance in the world,Is not between life and death,But when I stand in front or you,Yet you don't know that I love you.
f
front furthest
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/**
* Created with IntelliJ IDEA.
* Author: Amos
* E-mail: amos@amoscloud.com
* Date: 2021/3/8
* Time: 17:53
* Description:
*/
public class Main0027 {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String str = scanner.nextLine();
String pre = scanner.nextLine();
solution(str, pre);
}
}
private static void solution(String str, String pre) {
String[] words = str.split("\\W+");
Set<String> wordSet = new TreeSet<>(Arrays.asList(words));
StringBuilder builder = new StringBuilder();
for (String word : wordSet) {
if (word.startsWith(pre)) {
builder.append(word).append(" ");
}
}
if (builder.length() == 0) {
builder.append(pre);
}
System.out.println(builder.toString().trim());
}
}