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));
    }
}
相关推荐
微学AI1 小时前
Rust语言的深度剖析:内存安全与高性能的技术实现操作
java·安全·rust
zl_vslam1 小时前
SLAM中的非线性优-3D图优化之李群李代数在Opencv-PNP中的应用(四)
人工智能·opencv·算法·计算机视觉
程序猿小蒜1 小时前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
lsp程序员0101 小时前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
q***46522 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9992 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***25212 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
WX-bisheyuange2 小时前
基于Spring Boot的民谣网站的设计与实现
java·spring boot·后端
q***14642 小时前
Spring Boot文件上传
java·spring boot·后端
Run_Teenage3 小时前
C++:智能指针的使用及其原理
开发语言·c++·算法