Skip to content

Commit

Permalink
e100: Add rust impl of rearrange chars
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Sep 18, 2024
1 parent 2e991d6 commit d834199
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion src/od/2024e100/rearrange-chars/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,46 @@
// Copyright (c) 2024 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::io::{stdin, BufRead};

fn main() {
println!("Hello, world!");
// 创建计数数组
// 读取输入, 并统计所有字母出现的次数
// 统计出现的最多次数
// 然后逆向遍历所有的次数, 并打印结果
let mut chars = [0_usize; 256];
let mut line = String::new();
let ret = stdin().lock().read_line(&mut line);
assert!(ret.is_ok());

for byte in line.trim().bytes() {
let index: usize = byte as usize;
chars[index] += 1;
}

let max_count: usize = chars.iter().max().copied().unwrap();
let mut out = Vec::new();

for count in (1..=max_count).rev() {
// 遍历所有的小写字母
for byte in b'a'..=b'z' {
let index = byte as usize;
if chars[index] == count {
out.push(format!("{}:{count}", char::from_u32(byte as u32).unwrap()));
}
}

// 遍历所有的大写字母
for byte in b'A'..=b'Z' {
let index = byte as usize;
if chars[index] == count {
out.push(format!("{}:{count}", char::from_u32(byte as u32).unwrap()));
}
}
}

// 打印结果
let s = out.join(";");
println!("{s}");
}

0 comments on commit d834199

Please sign in to comment.