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

Function anagram_solution2

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

Source from the content-addressed store, hash-verified

1// anagram_solution2.rs
2
3fn anagram_solution2(s1: &str, s2: &str) -> bool {
4 if s1.len() != s2.len() {
5 return false;
6 }
7
8 // s1 和 s2 中的字符分别加入 vec_a, vec_b
9 let mut vec_a = Vec::new();
10 let mut vec_b = Vec::new();
11 for c in s1.chars() { vec_a.push(c); }
12 for c in s2.chars() { vec_b.push(c); }
13
14 // pos1、pos2 索引字符
15 let mut pos1: usize = 0;
16 let mut pos2: usize;
17
18 // 乱序字符串标示、控制循环
19 let mut is_anagram = true;
20
21 // 标示字符是否在 s2 中
22 let mut found: bool;
23
24 while pos1 < s1.len() && is_anagram {
25 pos2 = 0;
26 found = false;
27 while pos2 < vec_b.len() && !found {
28 if vec_a[pos1] == vec_b[pos2] {
29 found = true;
30 } else {
31 pos2 += 1;
32 }
33 }
34
35 // 某字符存在于 s2 中,将其替换成 ' ' 避免再次比较
36 if found {
37 vec_b[pos2]= ' ';
38 } else {
39 is_anagram = false;
40 }
41
42 // 处理 s1 中下一个字符
43 pos1 += 1;
44 }
45
46 is_anagram
47}
48
49fn main() {
50 let s1 = "rust";

Callers 1

mainFunction · 0.70

Calls 2

lenMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected