华为OD机试之英文输入法(Java源码)
英文输入法
题目描述
主管期望你来实现英文输入法单词联想功能。
需求如下:
依据用户输入的单词前缀,从已输入的英文语句中联想出用户想输入的单词,按字典序输出联想到的单词序列,
如果联想不到,请输出用户输入的单词前缀。
注意:
英文单词联想时,区分大小写
缩略形式如”don’t”,判定为两个单词,”don”和”t”
输出的单词序列,不能有重复单词,且只能是英文单词,不能有标点符号
输入描述
输入为两行。
首行输入一段由英文单词word和标点符号组成的语句str;
接下来一行为一个英文单词前缀pre。
0 < word.length() <= 20
0 < str.length <= 10000
0 < pre <= 20
输出描述
输出符合要求的单词序列或单词前缀,存在多个时,单词之间以单个空格分割
输入 | 输出 | 说明 |
---|---|---|
I love you He | He | 从用户已输入英文语句”I love you”中提炼出“I”、“love”、“you”三个单词,接下来用户输入“He”,\n\n从已输入信息中无法联想到任何符合要求的单词,因此输出用户输入的单词前缀。 |
The furthest distance in the world, Is not between life and death, But when I stand in front of you, Yet you don’t know that I love you. f | front furthest | 从用户已输入英文语句”The furthestdistance in the world, Is not between life and death, But when I stand in frontof you, Yet you dont know that I love you.”中提炼出的单词,符合“f”作为前缀的,有“furthest”和“front”,按字典序排序并在单词间添加空格后输出,结果为“front furthest”。 |
源码和解析
解析:
1.获取输入的所有字符,并拆分成子串数组(按空格) 注意处理缩略词don’t 为don和t
2.分别判断子串是否以用户输入的前缀开始
示例代码:
import java.util.ArrayList;
import java.util.Scanner;public class T12 {public static void main(String[] args) {System.out.println("请输入单词库(空格隔开):");Scanner scanner = new Scanner(System.in);String input1 = scanner.nextLine();System.out.println("请输入单词前缀:");String input2 = scanner.nextLine();ArrayList<String> wordList = new ArrayList<>();StringBuilder word = new StringBuilder();for (int i = 0; i < input1.length(); i++) {char c = input1.charAt(i);// 字符过滤if (!((c <= 'z' && c >= 'a') || (c <= 'Z' && c >= 'A'))) {if (word.length() > 0) {wordList.add(word.toString());word.setLength(0);}continue;};if (c == ' ') {if (word.length() > 0) {wordList.add(word.toString());word.setLength(0);}continue;}if (c == '\'') {if (word.length() > 0) {wordList.add(word.toString());word.setLength(0);}continue;}word.append(c);if (i == input1.length() - 1) {if (word.length() > 0) {wordList.add(word.toString());word.setLength(0);}}}boolean flag = false;// 是否找到for (String wd : wordList) {if (wd.startsWith(input2)) {flag = true;System.out.print(wd + " ");}}if (flag == false) {System.out.println(input2);}}
}