Skip to content

Commit cc01368

Browse files
committed
Resolve #213
1 parent b0c2b20 commit cc01368

5 files changed

+255
-0
lines changed

Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,7 @@ reqwest = "0.9.8"
99
serde = "1.0"
1010
serde_json = "1.0"
1111
serde_derive = "1.0"
12+
13+
[lib]
14+
doctest = false
15+
test = false

src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,6 @@ mod n0207_course_schedule;
178178
mod n0208_implement_trie_prefix_tree;
179179
mod n0209_minimum_size_subarray_sum;
180180
mod n0210_course_schedule_ii;
181+
mod n0211_add_and_search_word_data_structure_design;
182+
mod n0212_word_search_ii;
183+
mod n0213_house_robber_ii;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/**
2+
* [211] Add and Search Word - Data structure design
3+
*
4+
* Design a data structure that supports the following two operations:
5+
*
6+
*
7+
* void addWord(word)
8+
* bool search(word)
9+
*
10+
*
11+
* search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
12+
*
13+
* Example:
14+
*
15+
*
16+
* addWord("bad")
17+
* addWord("dad")
18+
* addWord("mad")
19+
* search("pad") -> false
20+
* search("bad") -> true
21+
* search(".ad") -> true
22+
* search("b..") -> true
23+
*
24+
*
25+
* Note:<br />
26+
* You may assume that all words are consist of lowercase letters a-z.
27+
*
28+
*/
29+
pub struct Solution {}
30+
31+
// submission codes start here
32+
33+
34+
struct WordDictionary {
35+
root: Option<Box<Trie>>,
36+
}
37+
38+
#[derive(Default)]
39+
struct Trie {
40+
is_end: bool,
41+
marked: Vec<usize>,
42+
nodes: [Option<Box<Trie>>; 26],
43+
}
44+
45+
impl Trie {
46+
fn new() -> Self {
47+
Default::default()
48+
}
49+
}
50+
51+
/**
52+
* `&self` means the method takes an immutable reference.
53+
* If you need a mutable reference, change it to `&mut self` instead.
54+
*/
55+
impl WordDictionary {
56+
// /** Initialize your data structure here. */
57+
// fn new() -> Self {
58+
// WordDictionary{
59+
// root: Some(Box::new(Trie::new())),
60+
// }
61+
// }
62+
63+
// /** Adds a word into the data structure. */
64+
// fn add_word(&mut self, word: String) {
65+
// let mut curr = self.root;
66+
67+
// for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) {
68+
// curr = curr.as_ref().unwrap().nodes[i];
69+
// }
70+
// curr.as_mut().unwrap().is_end = true;
71+
// }
72+
73+
// /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
74+
// fn search(&self, word: String) -> bool {
75+
// let mut chs: Vec<char> = word.chars().collect();
76+
// WordDictionary::search_from(self.root.as_ref(), &mut chs)
77+
// }
78+
79+
// fn search_from(node: Option<&Box<Trie>>, chs: &mut [char]) -> bool {
80+
// if node.is_none() {
81+
// return false
82+
// }
83+
// let node = node.unwrap();
84+
// if chs.len() < 1 {
85+
// return node.is_end
86+
// }
87+
// if chs[0] == '.' {
88+
// // backtracking
89+
// let mut sliced = &mut chs[1..];
90+
// for &idx in node.marked.iter() {
91+
// if WordDictionary::search_from(node.nodes[idx].as_ref(), sliced) {
92+
// return true
93+
// }
94+
// }
95+
// false
96+
// } else {
97+
// let next = node.nodes[(chs[0] as u8 - 'a' as u8) as usize].as_ref();
98+
// WordDictionary::search_from(next, &mut chs[1..])
99+
// }
100+
// }
101+
}
102+
103+
/**
104+
* Your WordDictionary object will be instantiated and called as such:
105+
* let obj = WordDictionary::new();
106+
* obj.add_word(word);
107+
* let ret_2: bool = obj.search(word);
108+
*/
109+
110+
// submission codes end
111+
112+
#[cfg(test)]
113+
mod tests {
114+
use super::*;
115+
116+
#[test]
117+
fn test_211() {
118+
// let mut dict = WordDictionary::new();
119+
// dict.add_word("bad".to_owned());
120+
// dict.add_word("dad".to_owned());
121+
// dict.add_word("mad".to_owned());
122+
// assert_eq!(dict.search("pad".to_owned()), false);
123+
// assert_eq!(dict.search("bad".to_owned()), true);
124+
// assert_eq!(dict.search(".ad".to_owned()), true);
125+
// assert_eq!(dict.search("da.".to_owned()), true);
126+
}
127+
128+
}

src/n0212_word_search_ii.rs

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* [212] Word Search II
3+
*
4+
* Given a 2D board and a list of words from the dictionary, find all words in the board.
5+
*
6+
* Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
7+
*
8+
*
9+
*
10+
* Example:
11+
*
12+
*
13+
* Input:
14+
* board = [
15+
* ['<span style="color:#d70">o</span>','<span style="color:#d70">a</span>','a','n'],
16+
* ['e','<span style="color:#d30">t</span>','<span style="color:#d00">a</span>','<span style="color:#d00">e</span>'],
17+
* ['i','<span style="color:#d70">h</span>','k','r'],
18+
* ['i','f','l','v']
19+
* ]
20+
* words = ["oath","pea","eat","rain"]
21+
*
22+
* Output: ["eat","oath"]
23+
*
24+
*
25+
*
26+
*
27+
* Note:
28+
*
29+
* <ol>
30+
* All inputs are consist of lowercase letters a-z.
31+
* The values of words are distinct.
32+
* </ol>
33+
*
34+
*/
35+
pub struct Solution {}
36+
37+
// submission codes start here
38+
// TODO
39+
40+
impl Solution {
41+
pub fn find_words(board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> {
42+
vec![]
43+
}
44+
}
45+
46+
// submission codes end
47+
48+
#[cfg(test)]
49+
mod tests {
50+
use super::*;
51+
52+
#[test]
53+
fn test_212() {}
54+
}

src/n0213_house_robber_ii.rs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* [213] House Robber II
3+
*
4+
* You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
5+
*
6+
* Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
7+
*
8+
* Example 1:
9+
*
10+
*
11+
* Input: [2,3,2]
12+
* Output: 3
13+
* Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
14+
* because they are adjacent houses.
15+
*
16+
*
17+
* Example 2:
18+
*
19+
*
20+
* Input: [1,2,3,1]
21+
* Output: 4
22+
* Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
23+
* Total amount you can rob = 1 + 3 = 4.
24+
*
25+
*/
26+
pub struct Solution {}
27+
28+
// submission codes start here
29+
30+
// DP twice: rob first one || not rob first one
31+
// F[i] = max(F[i-2] + num[i], F[i-1])
32+
impl Solution {
33+
pub fn rob(nums: Vec<i32>) -> i32 {
34+
let mut max = i32::min_value();
35+
for &rob_first in vec![true, false].iter() {
36+
let (mut prev, mut curr) = (0, 0);
37+
for (k, &num) in nums.iter().enumerate() {
38+
if k == 0 && !rob_first {
39+
continue
40+
}
41+
// k is last element but not the first element
42+
if k != 0 && k == (nums.len() - 1) && rob_first {
43+
continue
44+
}
45+
let next = i32::max(prev + num, curr);
46+
prev = curr;
47+
curr = next;
48+
}
49+
max = i32::max(max, curr)
50+
}
51+
max
52+
}
53+
}
54+
55+
// submission codes end
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
61+
#[test]
62+
fn test_213() {
63+
assert_eq!(Solution::rob(vec![2,3,2], 3));
64+
assert_eq!(Solution::rob(vec![1,2,3,1], 4));
65+
}
66+
}

0 commit comments

Comments
 (0)