牛客周赛 Round 48C:小红的01串取反

版本一

import java.util.Scanner;
import java.util.ArrayList;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    //取反
    public static String replaceCharAt(String str, int index, char ch) {
        if (str == null || index < 0 || index >= str.length()) {
            throw new IllegalArgumentException("Invalid index");
        }
        StringBuilder sb = new StringBuilder(str);
        if(ch=='0'){
            sb.setCharAt(index, '1');
        }
        else{
            sb.setCharAt(index, '0');
        }
        
        return sb.toString();
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            String a = in.nextLine();
            String b = in.nextLine();
            ArrayList<ArrayList<Integer>> operations= new ArrayList();
            if(n<2){
                System.out.println(-1);
            }
            else{
                int count = 0;
                for(int i = 0;i<a.length();i++){
                    if (a.charAt(i) != b.charAt(i)){
                        //replaceCharAt(a, i, a.charAt(i))的返回值应赋值给a,以便更新字符串。
                        a = replaceCharAt(a,i,a.charAt(i));
                        a = replaceCharAt(a,i+1,a.charAt(i+1));
                        count++;
                        ArrayList<Integer> operation = new ArrayList();
                        operation.add(i);
                        operation.add(i+1);
                        operations.add(operation);
                    }
                }
                if (a.equals(b)){
                    System.out.println(count);
                    for(ArrayList<Integer> operation:operations){
                        System.out.println((operation.get(0))+" "+operation.get(1));                       
                    }                    
                    }
                }
            }}
        }
  • 报错:
    请检查是否存在数组越界等非法访问情况 Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1540) at Main.main(Main.java:27)
  • 原因:
    第一行输入一个正整数n,代表字符串的长度。
    第二行输入一个长度为n的、仅由’0’和’1’组成的字符串。
    第三行输入一个长度为n的、仅由’0’和’1’组成的字符串。
    第一行读整数时,会漏掉一个换行符没有读,要多读一行消耗掉那个换行符,再读下面两行
  • 解决方案:
int n = in.nextInt();
            in.nextLine(); // 消耗换行符
            String a = in.nextLine();
            String b = in.nextLine();

结果:
运行超时10连重测中 rejudging 你的代码目前运行超时,但是有10次重测机会,10次重测之中,有通过即会变为AC Your code is TLE at present, but there are 10 rejudge. Among the 10 rejudge, if one rejudge passes, then AC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值