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));
    }
}
相关推荐
Han.miracle43 分钟前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
Le1Yu2 小时前
分布式事务以及Seata(XA、AT模式)
java
寒山李白3 小时前
关于Java项目构建/配置工具方式(Gradle-Groovy、Gradle-Kotlin、Maven)的区别于选择
java·kotlin·gradle·maven
mit6.8243 小时前
前后缀分解
算法
你好,我叫C小白3 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
无妄无望3 小时前
docker学习(4)容器的生命周期与资源控制
java·学习·docker
MC丶科4 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
千码君20164 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
夜白宋5 小时前
【word多文档docx合并】
java·word
@yanyu6665 小时前
idea中配置tomcat
java·mysql·tomcat