Skip to content

Commit bae9e4f

Browse files
committed
Add problem 3106: Lexicographically Smallest String After Operations With Constraint
1 parent dfa88a1 commit bae9e4f

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2089,6 +2089,7 @@ pub mod problem_3097_shortest_subarray_with_or_at_least_k_ii;
20892089
pub mod problem_3099_harshad_number;
20902090
pub mod problem_3101_count_alternating_subarrays;
20912091
pub mod problem_3105_longest_strictly_increasing_or_strictly_decreasing_subarray;
2092+
pub mod problem_3106_lexicographically_smallest_string_after_operations_with_constraint;
20922093
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
20932094

20942095
#[cfg(test)]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn get_smallest_string(s: String, k: i32) -> String {
7+
let mut s = s.into_bytes();
8+
let mut k = k.cast_unsigned();
9+
10+
for c in &mut s {
11+
let diff = u32::from(u8::min(*c - b'a', b'z' + 1 - *c));
12+
13+
if diff <= k {
14+
*c = b'a';
15+
k -= diff;
16+
} else {
17+
*c -= k as u8;
18+
19+
break;
20+
}
21+
}
22+
23+
String::from_utf8(s).unwrap()
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn get_smallest_string(s: String, k: i32) -> String {
31+
Self::get_smallest_string(s, k)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn get_smallest_string(s: String, k: i32) -> String;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(("zbbz", 3), "aaaz"), (("xaxcd", 4), "aawcd"), (("lol", 0), "lol")];
13+
14+
for ((s, k), expected) in test_cases {
15+
assert_eq!(S::get_smallest_string(s.to_string(), k), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)