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 7628e87

Browse files
committed
tries
1 parent dd8ea62 commit 7628e87

File tree

8 files changed

+291
-2
lines changed

8 files changed

+291
-2
lines changed

‎src/construct_tree.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use crate::TreeNode;
2+
use std::cell::RefCell;
3+
use std::rc::Rc;
4+
pub struct Solution {}
5+
impl Solution {
6+
pub fn build_tree(preorder: Vec<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
7+
if preorder.is_empty() || inorder.is_empty() {
8+
return None;
9+
}
10+
11+
let mid = inorder.iter().position(|&x| x == preorder[0]).unwrap();
12+
let root_node = Rc::new(RefCell::new(TreeNode::new(preorder[0])));
13+
let left = Self::build_tree(preorder[1..=mid].to_vec(), inorder[..mid].to_vec());
14+
let right = Self::build_tree(preorder[mid + 1..].to_vec(), inorder[mid..].to_vec());
15+
root_node.borrow_mut().left = left;
16+
root_node.borrow_mut().right = right;
17+
Some(root_node)
18+
}
19+
}

‎src/implement_trie.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::collections::HashMap;
2+
pub struct Trie {
3+
children: HashMap<char, Trie>,
4+
end: bool,
5+
}
6+
impl Trie {
7+
fn new() -> Self {
8+
Trie {
9+
end: false,
10+
children: HashMap::new(),
11+
}
12+
}
13+
fn insert(&mut self, word: String) {
14+
let mut cur = self;
15+
for c in word.chars() {
16+
cur = cur.children.entry(c).or_insert(Trie::new());
17+
}
18+
cur.end = true;
19+
}
20+
fn starts_with(&self, prefix: String) -> bool {
21+
let mut cur = self;
22+
for c in prefix.chars() {
23+
if cur.children.contains_key(&c) {
24+
cur = cur.children.get(&c).unwrap();
25+
} else {
26+
return false;
27+
}
28+
}
29+
true
30+
}
31+
fn search(&self, word: String) -> bool {
32+
let mut cur = self;
33+
for c in word.chars() {
34+
if let Some(node) = cur.children.get(&c) {
35+
cur = node;
36+
} else {
37+
return false;
38+
}
39+
}
40+
cur.end
41+
}
42+
}

‎src/kth_largest_stream.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
use std::cmp::Reverse;
2+
use std::collections::BinaryHeap;
3+
struct KthLargest {
4+
nums: Vec<i32>,
5+
k: i32,
6+
heap: BinaryHeap<Reverse<i32>>,
7+
}
8+
impl KthLargest {
9+
fn new(k: i32, nums: Vec<i32>) -> Self {
10+
let mut heap = BinaryHeap::new();
11+
for val in nums {
12+
heap.push(Reverse(val));
13+
if heap.len() > k as usize {
14+
heap.pop();
15+
}
16+
}
17+
println!("{:?}", heap);
18+
KthLargest { nums, k, heap }
19+
}
20+
fn add(&mut self, val: i32) -> i32 {
21+
self.heap.push(Reverse(val));
22+
self.heap.pop().unwrap();
23+
self.heap.peek().unwrap().0
24+
}
25+
}

‎src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
mod kth_smallest_bst;
2-
use kth_smallest_bst::Solution;
1+
mod word_search2;
32
use std::cell::RefCell;
43
use std::rc::Rc;
4+
use words_dictionary;
55
#[derive(Debug, PartialEq, Eq)]
66
pub struct TreeNode {
77
pub val: i32,

‎src/max_path_sum.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use crate::TreeNode;
2+
use std::cell::RefCell;
3+
use std::rc::Rc;
4+
pub struct Solution {}
5+
impl Solution {
6+
pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
7+
fn rec(root: Option<Rc<RefCell<TreeNode>>>, max: &mut i32) -> i32 {
8+
if let Some(node) = root {
9+
let node = node.borrow();
10+
let left = rec(node.left.clone(), max).max(0);
11+
let right = rec(node.right.clone(), max).max(0);
12+
let split = left + right + node.val;
13+
*max = std::cmp::max(*max, split);
14+
return node.val + std::cmp::max(left, right);
15+
}
16+
0
17+
}
18+
19+
let mut max = i32::MIN;
20+
std::cmp::max(rec(root, &mut max), max)
21+
}
22+
}

‎src/serialize_deserialize_bt.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use crate::TreeNode;
2+
use std::cell::RefCell;
3+
use std::rc::Rc;
4+
pub struct Codec {}
5+
impl Codec {
6+
fn new() -> Self {}
7+
fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String {
8+
self.preorder(root)
9+
}
10+
fn preorder(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String {
11+
let mut res = String::new();
12+
if let Some(node) = root {
13+
let node = node.borrow();
14+
res.push_str(&node.val.to_string());
15+
res.push(',');
16+
res.push_str(&self.preorder(node.left.clone()));
17+
res.push_str(&self.preorder(node.right.clone()));
18+
return res;
19+
}
20+
"null,".to_string()
21+
}
22+
23+
fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>> {
24+
let parts: Vec<&str> = data.split(',').collect();
25+
println!("{:?}", parts);
26+
fn rec(parts: &Vec<&str>, i: &mut usize) -> Option<Rc<RefCell<TreeNode>>> {
27+
let val = parts[*i];
28+
if parts[*i] == "null" {
29+
*i += 1;
30+
return None;
31+
}
32+
let mut node = Rc::new(RefCell::new(TreeNode::new(val.parse().unwrap())));
33+
*i += 1;
34+
let left = rec(parts, i);
35+
let right = rec(parts, i);
36+
node.borrow_mut().left = left;
37+
node.borrow_mut().right = right;
38+
Some(node)
39+
}
40+
rec(&parts, &mut 0)
41+
}
42+
}

‎src/word_search2.rs

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
pub struct Solution {}
2+
use std::collections::{HashMap, HashSet};
3+
pub struct Trie {
4+
end: bool,
5+
children: HashMap<char, Trie>,
6+
}
7+
impl Trie {
8+
fn new() -> Self {
9+
Trie {
10+
end: false,
11+
children: HashMap::new(),
12+
}
13+
}
14+
fn insert(&mut self, word: String) {
15+
let mut cur = self;
16+
for c in word.chars() {
17+
let cur = cur.children.entry(c).or_insert(Trie::new());
18+
}
19+
cur.end = true;
20+
}
21+
}
22+
impl Solution {
23+
pub fn find_words(board: Vec<Vec<char>>, words: Vec<String>) -> Vec<String> {
24+
let mut root = Trie::new();
25+
for w in words {
26+
root.insert(w);
27+
}
28+
let mut visted: HashSet<(i32, i32)> = HashSet::new();
29+
let mut res: Vec<String> = Vec::new();
30+
fn dfs(
31+
row: i32,
32+
col: i32,
33+
node: &mut Trie,
34+
word: &str,
35+
board: &Vec<Vec<char>>,
36+
res: &mut Vec<String>,
37+
visited: &mut HashSet<(i32, i32)>,
38+
) {
39+
if row < 0
40+
|| col < 0
41+
|| row as usize == board.len()
42+
|| col as usize == board[0].len()
43+
|| visited.contains(&(row, col))
44+
|| !node
45+
.children
46+
.contains_key(&board[row as usize][col as usize])
47+
{
48+
return;
49+
}
50+
visited.insert((row, col));
51+
52+
let mut cur = node
53+
.children
54+
.get_mut(&board[row as usize][col as usize])
55+
.unwrap();
56+
let mut new_word = word.to_string();
57+
new_word.push(board[row as usize][col as usize]);
58+
println!("{:?}", word);
59+
if cur.end {
60+
res.push(new_word.clone());
61+
}
62+
dfs(row + 1, col, &mut cur, &new_word, board, res, visited);
63+
dfs(row + 1, col, &mut cur, &new_word, board, res, visited);
64+
dfs(row, col + 1, &mut cur, &new_word, board, res, visited);
65+
dfs(row, col - 1, &mut cur, &new_word, board, res, visited);
66+
visited.remove(&(row, col));
67+
}
68+
let mut word = String::new();
69+
for r in 0..board.len() {
70+
for c in 0..board[0].len() {
71+
let mut word: Vec<char> = Vec::new();
72+
dfs(
73+
r as i32,
74+
c as i32,
75+
&mut root,
76+
&"",
77+
&board,
78+
&mut res,
79+
&mut visted,
80+
);
81+
}
82+
}
83+
res
84+
}
85+
}

‎src/words_dictionary.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
use std::collections::HashMap;
2+
3+
struct WordDictionary {
4+
children: HashMap<char, WordDictionary>,
5+
end: bool,
6+
}
7+
8+
/**
9+
* `&self` means the method takes an immutable reference.
10+
* If you need a mutable reference, change it to `&mut self` instead.
11+
*/
12+
impl WordDictionary {
13+
fn new() -> Self {
14+
WordDictionary {
15+
children: HashMap::new(),
16+
end: false,
17+
}
18+
}
19+
20+
fn add_word(&mut self, word: String) {
21+
let mut cur = self;
22+
for c in word.chars() {
23+
cur = cur.children.entry(c).or_insert(WordDictionary::new());
24+
}
25+
cur.end = true;
26+
}
27+
28+
fn search(&self, word: String) -> bool {
29+
fn dfs(root: &WordDictionary, word: String) -> bool {
30+
let mut cur = root;
31+
let mut i = 0;
32+
for c in word.chars() {
33+
if c == '.' {
34+
for node in cur.children.values() {
35+
let word = &word[i + 1..];
36+
if dfs(node, word.to_string()) {
37+
return true;
38+
}
39+
}
40+
return false;
41+
}
42+
if let Some(val) = cur.children.get(&c) {
43+
cur = val;
44+
} else {
45+
return false;
46+
}
47+
i += 1;
48+
}
49+
cur.end
50+
}
51+
dfs(self, word)
52+
}
53+
}
54+

0 commit comments

Comments
(0)

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