3228. 将 1 移动到末尾的最大操作次数

This commit is contained in:
li-chx 2025-11-21 09:38:40 +08:00
parent 4b8594e8e3
commit 93577c7ff2
1 changed files with 14 additions and 26 deletions

View File

@ -1,38 +1,26 @@
use std::collections::HashSet;
struct Solution; struct Solution;
impl Solution { impl Solution {
pub fn count_palindromic_subsequence(s: String) -> i32 { pub fn max_operations(s: String) -> i32 {
let s = s.as_bytes();
let mut ans = 0; let mut ans = 0;
let s = s.bytes().collect::<Vec<u8>>(); let mut ones = 0;
let mut set : HashSet<u8> = HashSet::new(); let mut first_zero = false;
for c in b'a'..=b'z' { for i in 0..s.len() {
set.clear(); if s[i] ==b'1' {
let (mut start,mut end) = (-1,0); ones += 1;
for i in 0..s.len() { first_zero = true;
if s[i] == c { }
start = i as i32; else {
break; if first_zero {
ans += ones;
first_zero = false;
} }
} }
if start == -1 {
continue;
}
for i in (0..s.len()).rev() {
if s[i] == c {
end = i;
break;
}
}
for i in (start+1)as usize..end {
set.insert(s[i]);
}
ans += set.len() as i32;
} }
ans ans
} }
} }
fn main() { fn main() {
let result = Solution::count_palindromic_subsequence(String::from("bbcbaba")); let result = Solution::max_operations(String::from("1001101"));
println!("{:?}", result); println!("{:?}", result);
} }