Skip to content

weekly-83 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
.PHONY: clean coverage

clean:
cargo clean
@cargo clean; \
rm *.profraw
test:
cargo test
@cargo test
coverage: test
grcov target/coverage/grcov.profraw --branch --ignore-not-existing --binary-path ./target/debug/ -s . -t lcov --ignore \"/*\" -o target/coverage/lcov.info
@grcov target/coverage/grcov.profraw --branch --ignore-not-existing --binary-path ./target/debug/ -s . -t lcov --ignore \"/*\" -o target/coverage/lcov.info
lint:
cargo fix --allow-dirty --allow-staged
@cargo fix --allow-dirty --allow-staged
2 changes: 2 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
- [LeetCode][leetcode]
- 语言: [Rust][rust]
- IDE: [我的 IDE 配置][我的ide 配置]
- 一些辅助工具
- [LaTeX公式编辑器](https://www.latexlive.com/##)

### 内容

Expand Down
198 changes: 197 additions & 1 deletion src/array/ext/disjoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl UnionFind {
}
root
}

pub fn is_connected(&self, p: usize, q: usize) -> bool {
self.find(p) == self.find(q)
}
Expand Down Expand Up @@ -74,7 +75,7 @@ pub fn find_circle_num(is_connected: Vec<Vec<i32>>) -> i32 {

/// [684. 冗余连接](https://leetcode.cn/problems/redundant-connection/)
pub fn find_redundant_connection(edges: Vec<Vec<i32>>) -> Vec<i32> {
let mut uf = UnionFind::new(edges.len()+1);
let mut uf = UnionFind::new(edges.len() + 1);
let mut curr_count = uf.count();
let mut last_edge = vec![];

Expand All @@ -90,11 +91,206 @@ pub fn find_redundant_connection(edges: Vec<Vec<i32>>) -> Vec<i32> {
last_edge
}

/// [990. 等式方程的可满足性](https://leetcode.cn/problems/satisfiability-of-equality-equations/)
pub fn equations_possible(equations: Vec<String>) -> bool {
let mut uf = UnionFind::new(26);

let mut not_equal = vec![]; // 暂存

for e in equations {
let s = e.as_bytes();
let (a, b, eq) = (s[0] - b'a', s[3] - b'a', s[1] == b'=');
if eq {
uf.connect(a as usize, b as usize);
} else {
not_equal.push((a as usize, b as usize));
}
}

for (a, b) in not_equal {
if uf.is_connected(a, b) {
return false;
}
}
true
}

/// [839. 相似字符串组](https://leetcode.cn/problems/similar-string-groups/)
pub fn num_similar_groups(strs: Vec<String>) -> i32 {
fn is_similar(s1: &str, s2: &str) -> bool {
s1.chars().zip(s2.chars()).filter(|(a, b)| !a.eq(b)).count() <= 2
}
let mut uf = UnionFind::new(strs.len());

for i in 0..strs.len() {
let s1 = strs.get(i).unwrap();
for j in i + 1..strs.len() {
if uf.is_connected(i, j) {
continue;
}

let s2 = strs.get(j).unwrap();
if is_similar(s1, s2) {
uf.connect(i, j);
}
}
}
uf.count() as i32
}

/// [841. 钥匙和房间](https://leetcode.cn/problems/keys-and-rooms/)
///
/// 关键信息: 除 `0` 号房间外的其余所有房间都被锁住
///
/// 解法1: bfs
/// ```
/// pub fn can_visit_all_rooms(rooms: Vec<Vec<i32>>) -> bool {
/// use std::collections::HashSet;
/// use std::collections::VecDeque;
///
/// let mut queue = VecDeque::new();
/// let mut visited = HashSet::new();
///
/// queue.push_back(0);
/// visited.insert(0);
/// while let Some(n) = queue.pop_front() {
/// let room = rooms.get(n).unwrap();
/// for &r in room.iter(){
/// if !visited.insert(r) {
/// continue;
/// }
/// queue.push_back(r as usize)
/// }
/// }
/// visited.len() == rooms.len()
/// }
/// ```
///
/// 解法二: 并查集
///
/// 由于 `HashSet` 这里也只是用了 `insert` 和 `contain` 两个方法, 因此换成 并查集判定也是OK的.
/// 甚至内存表现上, 并查集更优.
pub fn can_visit_all_rooms(rooms: Vec<Vec<i32>>) -> bool {
use std::collections::VecDeque;
let mut uf = UnionFind::new(rooms.len());

let mut queue = VecDeque::new();

queue.push_back(0);
while let Some(curr) = queue.pop_front() {
let room = rooms.get(curr).unwrap();
for &r in room.iter() {
if uf.is_connected(curr, r as usize) {
continue;
}
uf.connect(curr, r as usize);
queue.push_back(r as usize);
}
}
uf.count() == 1
}

#[cfg(test)]
mod test {
use super::*;
use crate::vec2;

#[test]
fn test_can_visit_all_rooms() {
struct Testcase {
rooms: Vec<Vec<i32>>,
expect: bool,
}

vec![
Testcase {
rooms: vec2![[1], [2], [3], []],
expect: true,
},
Testcase {
rooms: vec2![[1, 3], [3, 0, 1], [2], [0]],
expect: false,
},
Testcase {
rooms: vec2![[1], [], [0, 3], [1]],
expect: false,
},
]
.into_iter()
.enumerate()
.for_each(|(idx, testcase)| {
let Testcase { rooms, expect } = testcase;
let actual = can_visit_all_rooms(rooms);
assert_eq!(expect, actual, "case {} failed", idx);
});
}

#[test]
fn test_num_similar_groups() {
struct TestCase {
strs: Vec<&'static str>,
expect: i32,
}

vec![
TestCase {
strs: vec!["tars", "rats", "arts", "star"],
expect: 2,
},
TestCase {
strs: vec!["omv", "ovm"],
expect: 1,
},
]
.into_iter()
.enumerate()
.for_each(|(idx, testcase)| {
let TestCase { strs, expect } = testcase;
let strs = strs.into_iter().map(str::to_string).collect();
let actual = num_similar_groups(strs);
assert_eq!(expect, actual, "case {} failed", idx);
});
}

#[test]
fn test_equations_possible() {
struct TestCase {
equations: Vec<&'static str>,
expect: bool,
}

vec![
TestCase {
equations: vec!["a==b", "b!=a"],
expect: false,
},
TestCase {
equations: vec!["b==a", "a==b"],
expect: true,
},
TestCase {
equations: vec!["a==b", "b==c", "a==c"],
expect: true,
},
TestCase {
equations: vec!["a==b", "b!=c", "c==a"],
expect: false,
},
TestCase {
equations: vec!["c==c", "b==d", "x!=z"],
expect: true,
},
]
.into_iter()
.enumerate()
.for_each(|(idx, testcase)| {
let TestCase { equations, expect } = testcase;
let equations = equations.into_iter().map(str::to_string).collect();
let actual = equations_possible(equations);
assert_eq!(expect, actual, "case {} failed", idx);
});
}

#[test]
fn test_find_redundant_connection() {
struct Testcase {
Expand Down
Loading