1758. 生成交替二进制字符串的最少操作数

This commit is contained in:
li_chx 2026-03-05 08:45:56 +08:00
parent f8fd02dcb8
commit 566c6a8414
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 21 additions and 39 deletions

View File

@ -1,51 +1,33 @@
use std::cmp::min;
struct Solution; struct Solution;
mod arr; mod arr;
impl Solution { impl Solution {
pub fn num_special(mat: Vec<Vec<i32>>) -> i32 { pub fn min_operations(s: String) -> i32 {
let mut disable = vec![false; mat[0].len()]; let (mut cnt_a, mut cnt_b) = (0, 0);
let mut arr = vec![0; mat[0].len()]; let mut cnt = 0;
for i in 0..mat.len() { for c in s.chars() {
let mut disable_i = false; if cnt & 1 == 1 {
let mut next_do_disable = false; if c == '0' {
let mut last_index = 1000_usize; cnt_a += 1;
for j in 0..mat[0].len() { } else {
if mat[i][j] == 1 { cnt_b += 1;
if next_do_disable {
disable_i = true;
arr[last_index] = 0;
disable[last_index] = true;
disable[j] = true;
arr[j] = 0;
} }
if disable[j] { } else {
disable_i = true; if c == '0' {
continue; cnt_b += 1;
} } else {
if disable_i { cnt_a += 1;
disable[j] = true;
if arr[j] != 0 {
arr[j] = 0;
}
continue;
}
if arr[j] != 0 {
disable[j] = true;
arr[j] = 0;
disable_i = true;
continue
}
arr[j] += 1;
next_do_disable = true;
last_index = j;
} }
} }
cnt += 1;
} }
arr.iter().sum() min(cnt_a, cnt_b)
} }
} }
fn main() { fn main() {
let result = Solution::num_special(arr::make_matrix("[[0,0,0,0,0,0],[0,0,1,0,0,0],[0,0,0,0,1,0],[0,0,0,0,0,0],[0,0,1,0,0,1],[0,0,0,0,0,0],[0,0,0,0,0,0]]")); let result = Solution::min_operations("1111".to_string());
println!("{:?}", result); println!("{:?}", result);
} }
// [[0,0,0,0,0,0], // [[0,0,0,0,0,0],