2019春季暑期实习生正式批招聘笔试【腾讯】(回忆版)第一题

题目描述

给个字符串,这个字符串是由1和0组成,也就是说在这个字符串中只有1和0。

现在用一种消除方法:当1和0碰到一起的时候就会消除。无论1在前面,还是0在前面

不知道有没有玩过祖玛

2019春季暑期实习生正式批招聘笔试【腾讯】(回忆版)第一题

当图中黄球消除的时候,蓝球会碰到一起,也会消除。

例如当给字符串11110000,这种情况下,会全部消除干净。

例如当给字符串100101,这种情况下,会全部消除干净。

例如当给字符串01010,这种情况下,会留下最后的0。

输入

第一行 一个整数 n ,表示这个字符串的长度

第二行输入一个由1和0组成的字符串

输出

消除后剩下的长度

样例输入

8

11110000

样例输出

0

解题代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String string = '2' + scanner.next();
        boolean[] b = new boolean[n + 1];
        int c = 0;
        char start = '2';
        int start_index = 0;


        for (int i = 0; i <= n; i++) {

            char next = string.charAt(i);

            if (start == '1' && next == '0' || start == '0' && next == '1') {
                c += 2;
                b[start_index] = true;
                b[i] = true;
                for (int j = i; j >= 0; j--) {
                    if (!b[j]) {
                        start_index = j;
                        break;
                    }
                }

                start = string.charAt(start_index);
            } else {
                start_index = i;
                start = string.charAt(start_index);

            }

        }
        System.out.println(n - c);
        
    }
}

 

结果:

2019春季暑期实习生正式批招聘笔试【腾讯】(回忆版)第一题

2019春季暑期实习生正式批招聘笔试【腾讯】(回忆版)第一题 

通过全部样例