3517. 最小回文排列 I

This commit is contained in:
li-chx 2026-07-28 17:25:58 +08:00
parent 8cc7ce864c
commit fc8857537e
No known key found for this signature in database
GPG Key ID: 9EC03532D8AB7639
1 changed files with 21 additions and 21 deletions

View File

@ -1,32 +1,32 @@
use std::collections::HashMap;
mod arr; mod arr;
struct Solution {} struct Solution {}
impl Solution { impl Solution {
pub fn array_rank_transform(mut arr: Vec<i32>) -> Vec<i32> { pub fn smallest_palindrome(s: String) -> String {
if arr.len() == 0 { let mut arr = vec![0; 26];
return arr; let mut s = s.chars().collect::<Vec<char>>();
for i in 0..s.len() / 2 {
arr[(s[i] as u8 - b'a') as usize] += 1;
} }
let mut sorted_arr = arr.clone(); let mut idx = 0;
sorted_arr.sort_unstable(); for i in 0..26 {
let mut mp = HashMap::with_capacity(arr.len()); while arr[i] > 0 {
let mut sub = 0; s[idx] = (b'a' + i as u8) as char;
mp.insert(sorted_arr[0], 0); arr[i] -= 1;
for i in 1..sorted_arr.len() { idx += 1;
if sorted_arr[i] == sorted_arr[i-1] { }
sub+=1; }
continue; let mut rev_idx = idx;
} if s.len() % 2 != 0{
mp.insert(sorted_arr[i], i as i32 - sub); idx += 1;
} }
println!("{:?}", mp); while rev_idx > 0{
for x in arr.iter_mut() { rev_idx -= 1;
*x = *mp.get(x).unwrap() + 1; s[idx] = s[rev_idx];
} idx += 1;
arr }
s.into_iter().collect::<String>()
} }
} }
fn main() { fn main() {
println!("{:?}", Solution::array_rank_transform(vec![1,5,2,3,4,5])); println!("{:?}", Solution::smallest_palindrome("bahaahab".to_string()));
} }