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