【算法】程序猿不写代码是不对的70

package com.kingdz.algorithm.time201706;

/**
 * <pre>
 * 删除数字
 * 
 * http://judgecode.com/problems/1001
 * 
 * Given a string consists of only characters 0 and 1. You can only delete characters from it.
 * You want to change it into a string contains only alternating 0 and 1. Namely no Two consecutive characters are the same.
 * How many characters do you need to delete at least?
 * 
 * Input
 * A string consists of only characters 0 and 1 whose length is no longer than 100000.
 * 
 * Output
 * The least number of characters to delete.
 * </pre>
 * 
 * @author kingdz
 * 
 */
public class Algo14 {

    public static void main(String[] args) {
        String str = "1011";
        int delete = process(str);
        System.out.println(delete);
    }

    private static int process(String str) {
        // 获得第一位是0的情况下需要删除的字符数
        int first = startDelete(str, 0);
        // 获得第一位是1的情况下需要删除的字符数
        int secon = startDelete(str, 1);
        // 返回两个数中较小的数字就是需要删除的最少字符数
        return Math.min(first, secon);
    }

    private static int startDelete(String str, int expect) {
        // 删除计数
        int count = 0;
        for (char c : str.toCharArray()) {
            // 遍历每个字符
            String expectStr = "" + expect;
            // 判断每个字符是否是期望字符,如果不是就增加计数
            if (!expectStr.equals("" + c)) {
                count++;
                continue;
            }
            // 如果出现期望字符,则下一个期望字符就是0或1来回交替
            expect = (expect + 1) % 2;
        }
        return count;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值