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

在线评测平台提交代码遇Runtime Error,求排查(已通过样例)

Runtime Error排查:字符串子序列判断问题

我在在线评测平台提交代码时遇到Runtime Error。题目要求判断一个字符串是否是另一个字符串的子序列(即可以通过在后者中插入任意字符得到前者),输入为两个空格分隔的字符串。我的代码能通过所有给定样例,但提交报错,代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader instream = new BufferedReader(new InputStreamReader(System.in));
        String[] s;
        int index = 0;

        while((s = instream.readLine().split(" ")) != null){
            index = 0;

            for(int i = 0; i < s[1].length(); i++){
                if(s[0].charAt(index) == s[1].charAt(i))
                    index++;
                if(index == s[0].length())
                    break;
            }

            System.out.println(index == s[0].length() ? "Yes": "No");
        }
    }
}

报错原因分析

  • 空指针异常触发:instream.readLine()在流末尾会返回null,此时直接调用split(" ")会对null执行方法,抛出NullPointerException,你的循环条件逻辑错误。
  • 数组越界风险:
    • 若输入行无空格,split(" ")返回长度为1的数组,访问s[1]会抛出ArrayIndexOutOfBoundsException。
    • 若第一个字符串为空,s[0].charAt(index)会因字符串长度为0、index初始为0触发StringIndexOutOfBoundsException。
  • 输入格式未兼容:未处理输入行首尾空格、多个连续空格的情况,可能导致分割结果不符合预期。

修复后的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader instream = new BufferedReader(new InputStreamReader(System.in));
        String line;

        while((line = instream.readLine()) != null){
            // 处理首尾空白+任意多空格分割,兼容多样输入格式
            String[] s = line.trim().split("\\s+");
            // 确保输入包含两个有效字符串
            if(s.length < 2){
                System.out.println("No");
                continue;
            }
            String target = s[0];
            String source = s[1];
            int index = 0;

            // 空字符串是任何字符串的子序列
            if(target.isEmpty()){
                System.out.println("Yes");
                continue;
            }

            for(int i = 0; i < source.length(); i++){
                if(target.charAt(index) == source.charAt(i)){
                    index++;
                    if(index == target.length()){
                        break;
                    }
                }
            }

            System.out.println(index == target.length() ? "Yes": "No");
        }
    }
}

核心修复点

  1. 先读取完整行,判断行不为null后再执行分割,避免空指针异常。
  2. 使用trim()+split("\\s+")处理输入格式问题,兼容首尾空格、多连续空格的情况。
  3. 增加数组长度校验,防止访问不存在的数组元素。
  4. 单独处理空目标字符串的边界情况,避免字符访问越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:35:56