1415. 长度为 n 的开心字符串中字典序第 k 小的字符串

This commit is contained in:
li_chx 2026-03-14 13:10:03 +08:00
parent f91a4b2fe6
commit d5eafc86f4
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 48 additions and 59 deletions

View File

@ -1,72 +1,61 @@
use std::cmp::{max, Reverse};
use std::collections::BinaryHeap;
struct Solution; struct Solution;
mod arr; mod arr;
#[derive(Debug)]
struct Node {
time: i32,
cnt: i32,
}
impl Node {
fn new(time: i32, cnt: i32) -> Node {
Node { time,cnt }
}
fn total(&self) -> i64 {
let cnt = self.cnt as i64;
self.time as i64 * cnt * (cnt + 1) / 2
}
}
impl Ord for Node {
// 默认的比较方式
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.total().cmp(&other.total())
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.total().cmp(&other.total()))
}
}
impl Eq for Node { }
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.total() == other.total()
}
fn ne(&self, other: &Self) -> bool {
self.total() != other.total()
}
}
impl Solution { impl Solution {
pub fn min_number_of_seconds(mountain_height: i32, worker_times: Vec<i32>) -> i64 { pub fn construct(s: &mut Vec<char>, n: usize) {
let mut heap = BinaryHeap::<Reverse<Node>>::new(); for _ in s.len()..n {
for x in worker_times { if s[s.len() - 1] == 'a' {
heap.push(Reverse(Node::new(x, 1))); s.push('b');
} else {
s.push('a');
} }
for _ in 0..mountain_height {
let mut node = heap.pop().unwrap();
node.0.cnt += 1;
heap.push(node);
} }
let mut ans = 0_i64;
while !heap.is_empty() {
let mut node = heap.pop().unwrap().0;
node.cnt -= 1;
ans = max(ans, node.total())
} }
ans pub fn get_happy_string(n: i32, k: i32) -> String {
let n = n as usize;
let mut x = vec!['a'];
Self::construct(&mut x,n);
for _ in 1..k {
let mut have_ans = false;
for j in (0..n).rev() {
if x[j] == 'a' {
have_ans = true;
if j == 0{
x = vec!['b'];
Self::construct(&mut x,n);
break;
}
if x[j-1] == 'b'{
x[j] = 'c';
}else {
x[j] = 'b';
}
x = x[0..j+1].to_vec();
Self::construct(&mut x,n);
break;
}
if x[j] == 'b' {
if j == 0 || x[j-1] != 'c' {
x[j] = 'c';
x = x[0..j+1].to_vec();
Self::construct(&mut x,n);
have_ans = true;
break;
}
}
}
if !have_ans {
return String::new();
}
}
x.into_iter().collect()
} }
} }
fn main() { fn main() {
let result = Solution::min_number_of_seconds( let result = Solution::get_happy_string(
5, 10,
vec![1, 7], 100,
); );
println!("{:?}", result); println!("{:?}", result);
} }