Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3e43734

Browse files
committed
Add is_valid_anagram (frequency counter pattern)
1 parent 4dcf0bd commit 3e43734

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

‎labocédai/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
1+
pub mod problem_patterns;
12
pub mod sum_up_to;
23

34
#[cfg(test)]
45
mod tests {
6+
use crate::problem_patterns::*;
57
use crate::sum_up_to::*;
68

79
#[test]
810
fn test_sum_up_to() {
911
assert_eq!(sum_up_to(5), 5 + 4 + 3 + 2 + 1);
1012
assert_eq!(sum_up_to(0), 0);
1113
}
14+
15+
#[test]
16+
fn test_is_valid_anagram() {
17+
assert_eq!(is_valid_anagram("anagram", "nagaram"), true);
18+
assert_eq!(is_valid_anagram("rat", "car"), false);
19+
assert_eq!(is_valid_anagram("", ""), true);
20+
assert_eq!(is_valid_anagram("texttwisttime", "timetwisttext"), true);
21+
}
1222
}

‎labocédai/src/problem_patterns.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use std::collections::HashMap;
2+
3+
pub fn is_valid_anagram(string_1: &str, string_2: &str) -> bool {
4+
if string_1.len() != string_2.len() {
5+
return false;
6+
}
7+
let mut freq_counter = string_1
8+
.chars()
9+
.fold(HashMap::new(), |mut freq_counter, c| {
10+
*freq_counter.entry(c.to_string()).or_insert(0) += 1;
11+
freq_counter
12+
});
13+
for c in string_2.chars() {
14+
let count = freq_counter.entry(c.to_string()).or_insert(0);
15+
*count -= 1;
16+
if count < &mut 0 {
17+
return false;
18+
}
19+
}
20+
21+
return true;
22+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /