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

Function anagram_solution4

publication/code/chapter03/anagram_solution4.rs:3–33  ·  view source on GitHub ↗
(s1: &str, s2: &str)

Source from the content-addressed store, hash-verified

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

Callers 1

mainFunction · 0.70

Calls 1

lenMethod · 0.45

Tested by

no test coverage detected