You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现Word Break单词拆分问题输入ilike返回false排查

问题根因

你代码的问题确实出在字典输入逻辑,核心是Scanner.nextInt()方法只会读取整数数值,不会处理输入流中紧随整数之后的换行符,导致后续读取逻辑完全错位:

  • 输入示例中先输入10后敲击回车,sc.nextInt()仅读取了数值10,换行符\n残留在输入缓冲区
  • 首次调用sc.nextLine()时会直接读走这个空换行,导致dict[0]存入空字符串
  • 第二次调用sc.nextLine()会把第二行整句的i like sam sung mobile ice cream man go mango当做完整字符串存入dict[1],而非逐个读取单个单词
  • 后续循环还未读满10个字典元素,就已经把待判断的字符串ilike当做字典元素存入数组,最终字典集合中根本不存在单独的i、like单词,判断自然返回false。
修复方案

修改main方法的输入逻辑,读完整数后先吞掉残留换行,再使用sc.next()按空格分隔读取单个字典单词即可,修改后的完整代码如下:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class wordbreak {

    static Set<String> dictionary = new HashSet<>();
    public static boolean check(String str, int[] arr)
    {
        int n = str.length();
        if(n == 0)
            return true;
        if(arr[n] == -1)
        {
            arr[n] = 0;
            for(int i = 1; i <= n; i++)
            {
                String part = str.substring(0, i);
                if(dictionary.contains(part) && check(str.substring(i), arr))
                {
                    arr[n] = 1;
                    return true;
                }
            }
        }
        return arr[n] == 1;
    }
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        // 吞掉nextInt残留的换行符
        sc.nextLine();
        String dict[] = new String[n];
        for(int i = 0; i < n; i++)
        {
            // 用next()按空格分隔读取单个单词
            dict[i] = sc.next();
        }
        for(String i : dict)
        {
            dictionary.add(i);
        }
        // 吞掉读字典最后残留的换行
        sc.nextLine();
        String str = sc.nextLine();
        int arr[] = new int[str.length() + 1];
        Arrays.fill(arr, -1);
        System.out.println(check(str, arr));
    }
}

修改后输入示例中的测试用例,会正确返回true。

内容的提问来源于stack exchange,提问作者user13820412

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:18:04