Skip to content

Commit 8b80d6e

Browse files
committed
feat: build cache when start
1 parent 19e1b3c commit 8b80d6e

File tree

1 file changed

+16
-46
lines changed
  • maximum_product_of_word_lengths/src

1 file changed

+16
-46
lines changed

maximum_product_of_word_lengths/src/lib.rs

Lines changed: 16 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,31 @@
11
pub struct Solution {}
22

33
impl Solution {
4-
fn share_common_letters(
5-
mask_cache: &mut Vec<i32>,
6-
i1: usize,
7-
w1: &String,
8-
i2: usize,
9-
w2: &String,
10-
) -> bool {
11-
let mask1 = match mask_cache.get(i1) {
12-
Some(&x) if x != 0 => x,
13-
_ => {
14-
let mask = w1
15-
.chars()
16-
.fold(0, |acc, x| acc | 1 << (x as u8 - 'a' as u8));
17-
mask_cache[i1] = mask;
18-
mask
19-
}
20-
};
21-
let mask2 = match mask_cache.get(i2) {
22-
Some(&x) if x != 0 => x,
23-
_ => {
24-
let mask = w2
25-
.chars()
26-
.fold(0, |acc, x| acc | 1 << (x as u8 - 'a' as u8));
27-
mask_cache[i2] = mask;
28-
mask
29-
}
30-
};
31-
mask1 & mask2 != 0
4+
fn cal_mask(word: &String) -> i32 {
5+
word.chars()
6+
.fold(0, |acc, x| acc | 1 << (x as u8 - 'a' as u8))
327
}
338

34-
fn get_length(length_cache: &mut Vec<usize>, index: usize, word: &String) -> usize {
35-
match length_cache.get(index) {
36-
Some(&l) if l != 0 => l,
37-
_ => {
38-
let length = word.chars().count();
39-
length_cache[index] = length;
40-
length
41-
}
42-
}
9+
fn share_common_letters(mask_cache: &Vec<i32>, i1: usize, i2: usize) -> bool {
10+
let mask1 = mask_cache[i1];
11+
let mask2 = mask_cache[i2];
12+
mask1 & mask2 != 0
4313
}
4414

4515
pub fn max_product(words: Vec<String>) -> i32 {
46-
let mut length_cache = vec![0; words.len()];
47-
let mut mask_cache = vec![0; words.len()];
16+
let mut length_cache = Vec::with_capacity(words.len());
17+
let mut mask_cache = Vec::with_capacity(words.len());
18+
for word in words.iter() {
19+
length_cache.push(word.chars().count() as i32);
20+
mask_cache.push(Self::cal_mask(word));
21+
}
4822
let mut max = 0;
49-
for (i, w1) in words.iter().enumerate() {
23+
for i in 0..words.len() {
5024
for j in i + 1..words.len() {
51-
let w2 = &words[j];
52-
if Self::share_common_letters(&mut mask_cache, i, w1, j, w2) {
25+
if Self::share_common_letters(&mask_cache, i, j) {
5326
continue;
5427
}
55-
max = max.max(
56-
(Self::get_length(&mut length_cache, i, w1)
57-
* Self::get_length(&mut length_cache, j, w2)) as i32,
58-
);
28+
max = max.max(length_cache[i] * length_cache[j]);
5929
}
6030
}
6131
max

0 commit comments

Comments
 (0)