2024/10/15灵茶题单 滑动窗口

This commit is contained in:
Cool 2024-10-16 16:19:07 +08:00
parent f0d53cc2be
commit 41276c624f
1 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,55 @@
package com.cool.ling_cha_mount.sliding_windows;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/10/15/14:27
* @Description:
*/
public class Num1888 {
public int minFlips1(String s) {
int len = s.length();
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < len; i++) {
sb1.append(i % 2 == 0 ? '1' : '0');
sb2.append(i % 2 == 0 ? '0' : '1');
}
int[] count1 = new int[len];
int[] count2 = new int[len];
for (int i = 0; i < len; i++) {
count1[i] = (i > 0 ? count1[i - 1] : 0) + (s.charAt(i) == sb1.charAt(i) ? 0 : 1);
count2[i] = (i > 0 ? count2[i - 1] : 0) + (s.charAt(i) == sb2.charAt(i) ? 0 : 1);
}
int res = Math.min(count1[len - 1], count2[len - 1]);
if (len % 2 == 1) {
for (int i = 0; i < len; i++) {
res = Math.min(res, count1[i] + count2[len - 1] - count2[i]);
res = Math.min(res, count2[i] + count1[len - 1] - count1[i]);
}
return res;
} else {
return res;
}
}
public int minFlips(String s) {
int len = s.length();
int[] target=new int[]{'0','1'};
int count=0;
for(int i=0;i<len;i++){
count+=s.charAt(i)^target[i%2];
}
int min=Math.min(count,len-count);
if(len%2==0){
return min;
}else{
for(int i=1;i<len;i++){
count-=s.charAt(i-1)^target[(i-1)%2];
count+=s.charAt(i-1)^target[i%2];
min=Math.min(min,Math.min(count,len-count));
}
return min;
}
}
}