Java的第6个检查点没过报RE

P1320 压缩技术(续集版)

rookie2022 @ 2022-02-14 20:15:34

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        String line = sc.nextLine();
        sb.append(line);
        int N = line.toCharArray().length;
        //拼接成一行字符串
        for (int i = 1; i < N; i++) {
            sb.append(sc.nextLine());
        }
        String result = sb.toString();
        System.out.print(N+" ");
        //遍历字符串计算结果
        int countZero = 0;
        int countOne = 0;
        for (int i = 0; i < result.length(); i++) {
            if(i == 0 && result.charAt(0) == '1'){
                System.out.print(0 + " ");
               while(result.charAt(i) == '1'){
                   i++;
               }
                System.out.print(i +" ");
            }
            if(result.charAt(i) =='0'){
                if(i!=0 && result.charAt(i-1) == '1' && countOne!=0){
                    System.out.print(countOne + " ");
                }
                countOne = 0;
                countZero++;
            }
            if(result.charAt(i) == '1'){
                if(i!=0 && result.charAt(i-1) == '0' && countZero!=0){
                    System.out.print(countZero + " ");
                }
                countZero = 0;
                countOne++;
            }
        }
        if(result.charAt(result.length()-1) == '0'){
            System.out.println(countZero);
        }else {
            System.out.println(countOne);
        }
    }
}

by AirCnt @ 2022-02-14 20:37:49

逻辑改清楚了点


by AirCnt @ 2022-02-14 21:10:27

RE的原因是内循环 while(result.charAt(i) == '1'){ 及之后语句没有检查 i < result.length()

如果您愿意的话,应该像上面的代码或其他写法在一个更完整的过程内处理一段相同的字符。

可以的话,还能更像标程一点。 <- 链接


by rookie2022 @ 2022-02-15 12:36:18

@_Tabs 感谢赐教 o( ̄▽ ̄)ブ


by AirCnt @ 2022-02-15 13:14:07

@rookie2022 客气了


|