MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / anagram_solution4

Function anagram_solution4

code/chapter02/anagram_solution4.rs:1–28  ·  view source on GitHub ↗
(s1: &str, s2: &str)

Source from the content-addressed store, hash-verified

1fn anagram_solution4(s1: &str, s2: &str) -> bool {
2 if s1.len() != s2.len() { return false; }
3
4 // 大小为 26 的集合,用于将字符映射为 ASCII 值
5 let mut c1 = [0; 26];
6 let mut c2 = [0; 26];
7 for c in s1.chars() {
8 let pos = (c as usize) - 97; // 97 为 a 的 ASCII 值
9 c1[pos] += 1;
10 }
11 for c in s2.chars() {
12 let pos = (c as usize) - 97;
13 c2[pos] += 1;
14 }
15
16 // 逐个比较 ascii 值
17 let mut pos = 0;
18 let mut ok = true;
19 while pos < 26 && ok {
20 if c1[pos] == c2[pos] {
21 pos += 1;
22 } else {
23 ok = false;
24 }
25 }
26
27 ok
28}
29
30fn main() {
31 let s1 = "rust";

Callers 1

mainFunction · 0.70

Calls 1

lenMethod · 0.45

Tested by

no test coverage detected