use std::{cmp::Ordering, collections::HashMap};
impl Solution {
pub fn largest_palindromic(s: String) -> String {
if s == "" {
return String::from("");
}
let mut map: HashMap<i32, i32> = HashMap::new();
let n = s.len() as i32;
let sc: Vec<char> = s.chars().collect();
for i in 0..n {
let number = sc[i as usize] as i32 - '0' as i32;
map.insert(
number,
if map.contains_key(&number) {
map.get(&number).unwrap() + 1
} else {
1
},
);
}
let mut heap: Vec<Record> = vec![];
for (k, v) in map.iter() {
heap.push(Record::new(*k, *v));
}
heap.sort_by(compare);
let mut top = heap.remove(0);
if top.times == 1 {
return format!("{}", top.number);
} else if top.number == 0 {
heap.sort_by(compare);
return format!("{}", if heap.len() == 0 { 0 } else { heap[0].number });
} else {
let mut left = String::new();
left.push_str(&format!("{}", top.number));
top.times -= 2;
if top.times > 0 {
heap.push(top);
}
heap.sort_by(compare);
while heap.len() > 0 && heap[0].times > 1 {
top = heap.remove(0);
left.push_str(&format!("{}", top.number));
top.times -= 2;
if top.times > 0 {
heap.push(top);
}
heap.sort_by(compare);
}
let mut ans = String::new();
ans.push_str(&left);
if heap.len() > 0 {
heap.sort_by(compare);
ans.push_str(&format!("{}", heap[0].number));
}
let lc: Vec<char> = left.chars().collect();
let mut i = left.len() as i32 - 1;
while i >= 0 {
ans.push(lc[i as usize]);
i -= 1;
}
return ans;
}
}
}
fn compare(o1: &Record, o2: &Record) -> Ordering {
let l1 = Ordering::Greater;
let l2 = Ordering::Less;
if o1.times == 1 && o2.times > 1 {
return l1;
}
if o1.times > 1 && o2.times == 1 {
return l2;
}
if o2.number - o1.number > 0 {
return l1;
} else if o2.number - o1.number < 0 {
return l2;
} else {
return Ordering::Equal;
}
}
struct Record {
number: i32,
times: i32,
}
impl Record {
fn new(n: i32, t: i32) -> Self {
Self {
number: n,
times: t,
}
}
}
fn main() {
let ans = Solution::largest_palindromic(String::from("444947137"));
println!("ans = {:?}", ans);
}
struct Solution {}
评论