feat: add rust solution to lc problem: No.3443 (#4509)

No.3443.Maximum Manhattan Distance After K Changes
This commit is contained in:
Libin YANG 2025-06-20 06:43:54 +08:00 committed by GitHub
parent fe3eeb4a32
commit 9dcd740170
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 91 additions and 0 deletions

View File

@ -279,6 +279,38 @@ function maxDistance(s: string, k: number): number {
}
```
#### Rust
```rust
impl Solution {
pub fn max_distance(s: String, k: i32) -> i32 {
fn calc(s: &str, a: char, b: char, k: i32) -> i32 {
let mut ans = 0;
let mut mx = 0;
let mut cnt = 0;
for c in s.chars() {
if c == a || c == b {
mx += 1;
} else if cnt < k {
mx += 1;
cnt += 1;
} else {
mx -= 1;
}
ans = ans.max(mx);
}
ans
}
let a = calc(&s, 'S', 'E', k);
let b = calc(&s, 'S', 'W', k);
let c = calc(&s, 'N', 'E', k);
let d = calc(&s, 'N', 'W', k);
a.max(b).max(c).max(d)
}
}
```
<!-- tabs:end -->
<!-- solution:end -->

View File

@ -275,6 +275,38 @@ function maxDistance(s: string, k: number): number {
}
```
#### Rust
```rust
impl Solution {
pub fn max_distance(s: String, k: i32) -> i32 {
fn calc(s: &str, a: char, b: char, k: i32) -> i32 {
let mut ans = 0;
let mut mx = 0;
let mut cnt = 0;
for c in s.chars() {
if c == a || c == b {
mx += 1;
} else if cnt < k {
mx += 1;
cnt += 1;
} else {
mx -= 1;
}
ans = ans.max(mx);
}
ans
}
let a = calc(&s, 'S', 'E', k);
let b = calc(&s, 'S', 'W', k);
let c = calc(&s, 'N', 'E', k);
let d = calc(&s, 'N', 'W', k);
a.max(b).max(c).max(d)
}
}
```
<!-- tabs:end -->
<!-- solution:end -->

View File

@ -0,0 +1,27 @@
impl Solution {
pub fn max_distance(s: String, k: i32) -> i32 {
fn calc(s: &str, a: char, b: char, k: i32) -> i32 {
let mut ans = 0;
let mut mx = 0;
let mut cnt = 0;
for c in s.chars() {
if c == a || c == b {
mx += 1;
} else if cnt < k {
mx += 1;
cnt += 1;
} else {
mx -= 1;
}
ans = ans.max(mx);
}
ans
}
let a = calc(&s, 'S', 'E', k);
let b = calc(&s, 'S', 'W', k);
let c = calc(&s, 'N', 'E', k);
let d = calc(&s, 'N', 'W', k);
a.max(b).max(c).max(d)
}
}