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;
}
}
【算法】程序猿不写代码是不对的70
最新推荐文章于 2023-03-11 12:53:26 发布