Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
just have fun
  • Loading branch information
ben1009 committed Jul 10, 2025
commit 209f50425af4bcb8f6a4a65089978b97e82ace42
2 changes: 1 addition & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ concurrency:

env:
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
RUST_TOOLCHAIN: nightly-2025-02-01
RUST_TOOLCHAIN: ightly-2025-07-01

name: Check
jobs:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ concurrency:

env:
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
RUST_TOOLCHAIN: nightly-2025-02-01
RUST_TOOLCHAIN: nightly-2025-07-01

name: Test
jobs:
Expand Down
6 changes: 3 additions & 3 deletions Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ min_version = "0.36.10"
[tasks.install-nextest]
category = "Misc"
description = "install cargo-nextest"
install_crate = { crate_name = "cargo-nextest", version = "0.9.87", binary = "cargo", test_arg = [
install_crate = { crate_name = "cargo-nextest", version = "0.9.96", binary = "cargo", test_arg = [
"nextest",
"--help",
] }
Expand Down Expand Up @@ -50,7 +50,7 @@ args = ["fmt", "--all"]
[tasks.check-typos]
category = "Dev - check"
description = "Run cargo typos-cli check"
install_crate = { version = "1.28.4", crate_name = "typos-cli", binary = "typos", test_arg = [
install_crate = { version = "1.32.0", crate_name = "typos-cli", binary = "typos", test_arg = [
"--help",
] }
script = """
Expand Down Expand Up @@ -80,7 +80,7 @@ cargo hakari verify > /dev/null
[tasks.check-machete]
category = "Dev - check"
description = "Run cargo machete check"
install_crate = { version = "0.7.0", crate_name = "cargo-machete", binary = "cargo", test_arg = [
install_crate = { version = "0.8.0", crate_name = "cargo-machete", binary = "cargo", test_arg = [
"machete",
"--help",
] }
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "nightly-2025-02-01"
channel = "nightly-2025-07-01"
29 changes: 13 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ fn main() {
} else {
_id = id_arg
.parse::<u32>()
.unwrap_or_else(|_| panic!("not a number: {}", id_arg));
.unwrap_or_else(|_| panic!("not a number: {id_arg}"));
if initialized_ids.contains(&_id) {
println!("The problem you chose has been initialized in problem/");
continue;
Expand All @@ -129,9 +129,8 @@ fn main() {

let problem = fetcher::get_problem(_id).unwrap_or_else(|| {
panic!(
"Error: failed to get problem #{} \
(The problem may be paid-only or may not be exist).",
_id
"Error: failed to get problem #{_id} \
(The problem may be paid-only or may not be exist)."
)
});
let code = problem.code_definition.iter().find(|&d| d.value == *"rust");
Expand All @@ -157,9 +156,8 @@ fn generate_random_id(except_ids: &[u32]) -> u32 {
return res;
}
println!(
"Generate a random num ({}), but it is invalid (the problem may have been solved \
or may have no rust version). Regenerate..",
res
"Generate a random num ({res}), but it is invalid (the problem may have been solved \
or may have no rust version). Regenerate.."
);
}
}
Expand Down Expand Up @@ -291,7 +289,7 @@ fn deal_solving(id: &u32) {
problem.question_id,
problem.title_slug.replace('-', "_")
);
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));
let file_path = Path::new("./src/problem").join(format!("{file_name}.rs"));
// check problem/ existence
if !file_path.exists() {
panic!("problem does not exist");
Expand All @@ -302,15 +300,15 @@ fn deal_solving(id: &u32) {
problem.question_id,
problem.title_slug.replace('-', "_")
);
let solution_path = Path::new("./src/solution").join(format!("{}.rs", solution_name));
let solution_path = Path::new("./src/solution").join(format!("{solution_name}.rs"));
if solution_path.exists() {
panic!("solution exists");
}
// rename/move file
fs::rename(file_path, solution_path).unwrap();
// remove from problem/mod.rs
let mod_file = "./src/problem/mod.rs";
let target_line = format!("mod {};", file_name);
let target_line = format!("mod {file_name};");
let lines: Vec<String> = io::BufReader::new(File::open(mod_file).unwrap())
.lines()
.map(|x| x.unwrap())
Expand All @@ -322,7 +320,7 @@ fn deal_solving(id: &u32) {
.append(true)
.open("./src/solution/mod.rs")
.unwrap();
let _ = writeln!(lib_file, "mod {};", solution_name);
let _ = writeln!(lib_file, "mod {solution_name};");
}

fn deal_problem(problem: &Problem, code: &CodeDefinition, write_mod_file: bool) {
Expand All @@ -331,8 +329,7 @@ fn deal_problem(problem: &Problem, code: &CodeDefinition, write_mod_file: bool)
problem.question_id,
problem.title_slug.replace('-', "_")
);
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));

let file_path = Path::new("./src/problem").join(format!("{file_name}.rs"));
let template = fs::read_to_string("./template.rs").unwrap();
let source = template
.replace("__PROBLEM_TITLE__", &problem.title)
Expand Down Expand Up @@ -361,7 +358,7 @@ fn deal_problem(problem: &Problem, code: &CodeDefinition, write_mod_file: bool)
.append(true)
.open("./src/problem/mod.rs")
.unwrap();
let _ = writeln!(lib_file, "pub mod {};", file_name);
let _ = writeln!(lib_file, "pub mod {file_name};");
}
}

Expand All @@ -378,9 +375,9 @@ mod test {
// pub mod p0001_two_sum;
pub mod p0002_add_two_numbers;
pub mod p0003_longest_substring_without_repeating_characters;"#;
writeln!(file, "{}", content).unwrap();
writeln!(file, "{content}").unwrap();
let ids = get_initialized_ids(path.to_str().unwrap());
println!("{:?}", ids);
println!("{ids:?}");
assert!(ids.len() == 2);
assert!(ids[0] == 2);
assert!(ids[1] == 3);
Expand Down
1 change: 1 addition & 0 deletions src/problem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub mod p1016_binary_string_with_substrings_representing_1_to_n;
pub mod p1054_distant_barcodes;
pub mod p1186_maximum_subarray_sum_with_one_deletion;
pub mod p1376_time_needed_to_inform_all_employees;
pub mod p1608_special_array;
pub mod p2437_number_of_valid_clock_times;
pub mod p2671_frequency_tracker;
pub mod p2708_maximum_strength_of_a_group;
Expand Down
15 changes: 6 additions & 9 deletions src/problem/p0014_longest_common_prefix.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::cmp;

/// [14] Longest Common Prefix
///
/// Write a function to find the longest common prefix string amongst an array of strings.
Expand Down Expand Up @@ -32,23 +30,22 @@ pub struct Solution {}
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.len() == 1 {
return strs[0].clone();
return strs[0].to_string();
}

let mut ret = strs[0].as_bytes();
let mut ret = strs[0].to_string();
for str in strs.iter().skip(1) {
let t = str.as_bytes();
let mut j = 0;
while j < cmp::min(ret.len(), t.len()) {
if ret[j] != t[j] {
while j < std::cmp::min(ret.len(), str.len()) {
if ret.as_bytes()[j] != str.as_bytes()[j] {
break;
}
j += 1;
}
ret = &ret[0..j];
ret = ret[..j].to_string();
}

String::from_utf8_lossy(ret).to_string()
ret
}
}

Expand Down
16 changes: 9 additions & 7 deletions src/problem/p0017_letter_combinations_of_a_phone_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct Solution {}
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.is_empty() {
return Vec::new();
return vec![];
}

let dic = HashMap::from([
Expand All @@ -51,26 +51,28 @@ impl Solution {
]);

let mut ret = vec![];
Self::dfs(digits.as_bytes(), 0, &dic, &mut vec![], &mut ret);
Self::dfs(digits.as_bytes(), &dic, 0, &mut vec![], &mut ret);

ret
}

fn dfs(
digits: &[u8],
idx: usize,
dic: &HashMap<u8, &str>,
idx: usize,
tmp: &mut Vec<u8>,
ret: &mut Vec<String>,
) {
if tmp.len() == digits.len() {
ret.push(String::from_utf8(tmp.clone()).unwrap());
ret.push(String::from_utf8_lossy(tmp).to_string());

return;
}

for c in dic[&digits[idx]].as_bytes() {
tmp.push(*c);
Self::dfs(digits, idx + 1, dic, tmp, ret);
let s = dic[&digits[idx]].as_bytes();
for item in s {
tmp.push(*item);
Solution::dfs(digits, dic, idx + 1, tmp, ret);
tmp.pop();
}
}
Expand Down
15 changes: 8 additions & 7 deletions src/problem/p0019_remove_nth_node_from_end_of_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,17 @@ use crate::util::linked_list::ListNode;
// }
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut root_pointer = ListNode { val: 0, next: head };
let mut root_pointer = ListNode::new(0);
root_pointer.next = head.clone();
let mut pre = &mut root_pointer;
let mut current = &pre.clone();
for _i in 0..n {
current = current.next.as_ref().unwrap();
}
let mut head = head.as_ref().unwrap();

while let Some(ref n) = current.next {
current = n;
for _ in 1..n {
head = head.next.as_ref().unwrap();
}
while let Some(n) = head.next.as_ref() {
pre = pre.next.as_mut().unwrap();
head = n;
}
pre.next = pre.next.as_mut().unwrap().next.take();

Expand Down
18 changes: 7 additions & 11 deletions src/problem/p0020_valid_parentheses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,20 +43,16 @@ impl Solution {
return false;
}

let dic = HashMap::from([(')', '('), (']', '['), ('}', '{')]);
let mut stack = vec![];
let s = s.as_bytes();
let map = HashMap::from([(b'}', b'{'), (b')', b'('), (b']', b'[')]);
for v in s {
if let Some(t) = stack.last() {
if let Some(p) = map.get(v) {
if p == t {
stack.pop();
continue;
}
for c in s.chars() {
if let t @ Some(_) = stack.last() {
if t == dic.get(&c) {
stack.pop();
}
} else {
stack.push(c);
}

stack.push(*v);
}

stack.is_empty()
Expand Down
23 changes: 13 additions & 10 deletions src/problem/p0022_generate_parentheses.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::vec;

/// [22] Generate Parentheses
///
/// Given n pairs of parentheses, write a function to generate all combinations of well-formed
Expand All @@ -22,26 +24,27 @@ pub struct Solution {}
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let mut ret = vec![];
Self::gen(n, 0, 0, &mut vec![], &mut ret);
Solution::gen(n, 0, 0, &mut vec![], &mut ret);

ret
}

fn gen(n: i32, l: i32, r: i32, tmp: &mut Vec<u8>, ret: &mut Vec<String>) {
if tmp.len() == n as usize * 2 {
ret.push(String::from_utf8(tmp.clone()).unwrap());
fn gen(n: i32, l: i32, r: i32, t: &mut Vec<u8>, ret: &mut Vec<String>) {
if t.len() == n as usize * 2 {
ret.push(String::from_utf8_lossy(t).to_string());

return;
}

if l < n {
tmp.push(b'(');
Self::gen(n, l + 1, r, tmp, ret);
tmp.pop();
t.push(b'(');
Solution::gen(n, l + 1, r, t, ret);
t.pop();
}
if r < l {
tmp.push(b')');
Self::gen(n, l, r + 1, tmp, ret);
tmp.pop();
t.push(b')');
Solution::gen(n, l, r + 1, t, ret);
t.pop();
}
}
}
Expand Down
21 changes: 9 additions & 12 deletions src/problem/p0023_merge_k_sorted_lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
/// lists[i] is sorted in ascending order.
/// The sum of lists[i].length will not exceed 10^4.
pub struct Solution {}
use std::collections::BinaryHeap;
use std::{cmp::Reverse, collections::BinaryHeap};

use crate::util::linked_list::ListNode;

Expand Down Expand Up @@ -68,21 +68,18 @@ impl Solution {
}

let mut ret = ListNode::new(0);
let mut current = &mut ret;
let mut head = &mut ret;
let mut heap = BinaryHeap::new();

for list in lists.into_iter().flatten() {
heap.push(std::cmp::Reverse(list));
heap.push(Reverse(list));
}

while let Some(std::cmp::Reverse(l)) = heap.pop() {
current.next = Some(Box::new(ListNode {
val: l.val,
next: None,
}));
current = current.next.as_mut().unwrap();
if let Some(l) = l.next {
heap.push(std::cmp::Reverse(l));
while let Some(Reverse(mut t)) = heap.pop() {
let n = t.next.take();
head.next = Some(t);
head = head.next.as_mut().unwrap();
if let Some(n) = n {
heap.push(Reverse(n));
}
}

Expand Down
7 changes: 3 additions & 4 deletions src/problem/p0027_remove_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,11 @@ impl Solution {
let mut lo = 0;
while lo as i32 <= hi {
if nums[lo] == val {
nums[lo] = nums[hi as usize];
nums.swap(lo, hi as usize);
hi -= 1;
continue;
} else {
lo += 1;
}

lo += 1;
}

hi + 1
Expand Down
Loading