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));
    }
}
相关推荐
春和景明36011 小时前
mysql复习
java
宇木灵11 小时前
C语言基础-六、指针
c语言·开发语言·学习·算法
苦藤新鸡11 小时前
64 搜索平移递增数组中的元素
数据结构·算法
百锦再11 小时前
Java InputStream和OutputStream实现类完全指南
java·开发语言·spring boot·python·struts·spring cloud·kafka
Vic1010111 小时前
链表算法三道
java·数据结构·算法·链表
再难也得平11 小时前
[LeetCode刷题]128.最长连续序列(从零开始的java题解)
java·算法·leetcode
亓才孓11 小时前
【MyBatis Exception】SQLSyntaxErrorException(按批修改不加配置会报错)
java·开发语言·mybatis
xiaoye-duck11 小时前
《算法题讲解指南:优选算法-双指针》--05有效三角形的个数,06查找总价值为目标值的两个商品
c++·算法
亓才孓11 小时前
【MyBatis Runtime Exception】自动驼峰映射对Map不生效,应该在查询中起别名
java·windows·mybatis
ArturiaZ11 小时前
【day31】
开发语言·c++·算法