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));
    }
}
相关推荐
冼紫菜2 分钟前
Spring Cloud 项目中优雅地传递用户信息:基于 Gateway + ThreadLocal 的用户上下文方案
java·开发语言·spring boot·后端·spring cloud·gateway
为美好的生活献上中指3 分钟前
java每日精进 4.29【框架之自动记录日志并插入如数据库流程分析】
java·linux·数据库
import_random5 分钟前
[社交网络]布局算法(可视化)
算法
初心_20248 分钟前
2. python协程/异步编程详解
java·前端·python
camellia9 分钟前
SpringBoot(三十九)SpringBoot集成RabbitMQ实现流量削峰添谷
java·后端
camellia10 分钟前
SpringBoot(三十七)SpringBoot开启gzip压缩提高网站性能
java·后端
乐予吕11 分钟前
手写一个微型 Spring 框架(二):从路由到生命周期管理
java·后端·spring
NRlovestudy11 分钟前
JAVA使用Apache POI导出Word,支持向表格动态添加多行数据
java
camellia13 分钟前
SpringBoot(四十)SpringBoot集成RabbitMQ使用过期时间+死信队列实现延迟队列
java·后端
camellia13 分钟前
SpringBoot(三十)Springboot使用CGLIB动态代理
java·后端