OJ-1017中文分词模拟器

示例0

输入:

ilovechina

i,ilove,lo,love,ch,china,lovechina

输出:

ilove,china

示例1

输入:

ilovechina

i,love,china,ch,na,ve,lo,this,is,the,word

输出:

i,love,china

说明:

示例2

输入:

iat

i,love,china,ch,na,ve,lo,this,is,the,word,beauti,tiful,ful

输出:i,a,t

说明:单个字母,不在词库中且不成词则直接输出单个字母

示例3

输入:

ilovechina,thewordisbeautiful

i,love,china,ch,na,ve,lo,this,is,the,word,beauti,tiful,ful

输出:

i,love,china,the,word,is,beauti,ful

说明:标点符号为英文标点符号

复制代码
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;


public class 中文模拟分词器2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        List<String> dict = Arrays.asList(in.nextLine().split(","));
        
        int len = input.length();
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < len) {
            int j = len;
            boolean found = false;
            while (j > i) {
                String s = input.substring(i, j);
                if (s.matches("[a-zA-Z]+") && (dict.contains(s) || s.length() == 1)) {
                    sb.append(s).append(",");
                    found = true;
                    i = j;
                    break;
                }
                j--;
            }
            if (!found) {
                i++;
            }
        }
        System.out.println(sb.substring(0, sb.length() - 1));
    }
}
相关推荐
毕设源码-邱学长8 小时前
【开题答辩全过程】以 基于Springboot个人健康运动系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
愿你天黑有灯下雨有伞8 小时前
Spring Boot + FastExcel:打造完美的导入校验功能
java·spring boot·后端
Rainly20008 小时前
java原生实现企业级spring batch数据迁移
java·spring·batch
Hello World . .8 小时前
排序算法:常用排序算法
c语言·数据结构·算法·vim·排序算法
綦枫Maple8 小时前
IDEA选择“在当前窗口打开”还是“新窗口打开”的提示不见了,如何恢复?
java·ide·intellij-idea
缺一句感谢和缺一句道歉8 小时前
Module was compiled with an incompatible version of Kotlin.
java·kotlin
码云数智-大飞8 小时前
优雅解决 IntelliJ IDEA “命令行过长”问题:使用 JAR 清单(Manifest)方式
java·intellij-idea·jar
毕设源码-赖学姐8 小时前
【开题答辩全过程】以 基于Spring Boot的驾校信息管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
代码方舟8 小时前
Java后端实战:对接天远车辆过户查询API打造自动化车况评估系统
java·开发语言·自动化