diff options
138 files changed, 2362 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5e1b333 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +main diff --git a/_missing/Cargo.toml b/_missing/Cargo.toml new file mode 100644 index 0000000..b3979a3 --- /dev/null +++ b/_missing/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "leetcode" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/_missing/src/main.rs b/_missing/src/main.rs new file mode 100644 index 0000000..4d903d1 --- /dev/null +++ b/_missing/src/main.rs @@ -0,0 +1,37 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec![100,4,200,1,3,2], 4), + (vec![0,3,7,2,5,8,4,6,0,1], 9) + ]; + + for test in tests { + println!("{:?} is {} should be {}", test.0, Solution::longest_consecutive(test.0.clone()), test.1); + } +} + + +struct Solution; + +impl Solution { + pub fn longest_consecutive(nums: Vec<i32>) -> i32 { + let mut s = nums.clone(); + s.sort(); + s.dedup(); + let mut longest = (nums.len() > 0) as i32; + let mut longest_old = 0; + + for i in s.windows(2) { + if &i[1] != &(&i[0] + 1) { + if longest > longest_old { + longest_old = longest; + } + longest = 1; + continue; + } + longest += 1; + } + + longest.max(longest_old) + } +} diff --git a/a-number-after-a-double-reversal/Cargo.toml b/a-number-after-a-double-reversal/Cargo.toml new file mode 100644 index 0000000..38924b9 --- /dev/null +++ b/a-number-after-a-double-reversal/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "a-number-after-a-double-reversal" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/a-number-after-a-double-reversal/src/main.rs b/a-number-after-a-double-reversal/src/main.rs new file mode 100644 index 0000000..7e7c9d1 --- /dev/null +++ b/a-number-after-a-double-reversal/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn is_same_after_reversals(num: i32) -> bool { + num == 0 || num % 10 != 0 + } +} diff --git a/add-two-numbers/Cargo.toml b/add-two-numbers/Cargo.toml new file mode 100644 index 0000000..eee98ac --- /dev/null +++ b/add-two-numbers/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-two-numbers" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/add-two-numbers/src/main.rs b/add-two-numbers/src/main.rs new file mode 100644 index 0000000..3a9abe9 --- /dev/null +++ b/add-two-numbers/src/main.rs @@ -0,0 +1,46 @@ +fn main() { + println!("Hello, world!"); +} + +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option<Box<ListNode>> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} +// Comprehensive 3ms Recursive + +struct Solution {} +impl Default for ListNode { + fn default() -> Self { + ListNode::new(0) + } +} + +impl Solution { + pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { + Solution::add_two_numbers_with_carry(l1, l2, 0) + } + pub fn add_two_numbers_with_carry(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, carry: i32) -> Option<Box<ListNode>> { + if l1.is_none() && l2.is_none() && carry == 0 {return None;} + let a = l1.unwrap_or_default(); + let b = l2.unwrap_or_default(); + let sum = a.val + b.val + carry; + + let result = ListNode { + val: sum % 10, + next: Solution::add_two_numbers_with_carry(a.next, b.next, sum / 10) + }; + Some(Box::new(result)) + } +} + diff --git a/buddy-strings/Cargo.toml b/buddy-strings/Cargo.toml new file mode 100644 index 0000000..c7ee668 --- /dev/null +++ b/buddy-strings/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "buddy-strings" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/buddy-strings/src/main.rs b/buddy-strings/src/main.rs new file mode 100644 index 0000000..dbc982c --- /dev/null +++ b/buddy-strings/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("ab", "ba", true), + ("ab", "ab", false), + ("aa", "aa", true), + ("abcaa", "abcbb", false) + ]; + + for test in tests { + println!("{:?} {:?} is {} should be {}", test.0, test.1, + Solution::buddy_strings(test.0.clone().to_string(), test.1.clone().to_string()), + test.2); + } +} +struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn buddy_strings(s: String, goal: String) -> bool { + let mut occurences_s = HashMap::new(); + let mut occurences_goal = HashMap::new(); + let similarities = s.chars().zip(goal.chars()).filter(|(a,b)| { + *occurences_s.entry(a.clone()).or_insert(1) += 1; + *occurences_goal.entry(b.clone()).or_insert(1) += 1; + a != b}) + .count(); + s.len() == goal.len() && occurences_s == occurences_goal && (similarities == 2 || (similarities == 0 && occurences_s.values().any(|&x| x > 2))) + } +} diff --git a/candy/Cargo.toml b/candy/Cargo.toml new file mode 100644 index 0000000..40dd834 --- /dev/null +++ b/candy/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "candy" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/candy/src/main.rs b/candy/src/main.rs new file mode 100644 index 0000000..e2fe56c --- /dev/null +++ b/candy/src/main.rs @@ -0,0 +1,18 @@ +fn main() { + println!("Hello, world!"); +} + + +struct Solution {} +impl Solution { + pub fn candy(ratings: Vec<i32>) -> i32 { + let result = Vec::with_capacity(ratings.len()); + + let mut candy = 1; + + while let Some(s)= ratings.iter().enumerate() + .fold(i32::MAX, |acc, (i,v)| if v < acc && {v}) + + result.iter().sum::<i32>() + } +} diff --git a/check-if-a-string-contains-all-binary-codes-of-size-k/Cargo.toml b/check-if-a-string-contains-all-binary-codes-of-size-k/Cargo.toml new file mode 100644 index 0000000..9086b45 --- /dev/null +++ b/check-if-a-string-contains-all-binary-codes-of-size-k/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "check-if-a-string-contains-all-binary-codes-of-size-k" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/check-if-a-string-contains-all-binary-codes-of-size-k/src/main.rs b/check-if-a-string-contains-all-binary-codes-of-size-k/src/main.rs new file mode 100644 index 0000000..028b32c --- /dev/null +++ b/check-if-a-string-contains-all-binary-codes-of-size-k/src/main.rs @@ -0,0 +1,32 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("00110110", 2, true), + ("0110", 1, true), + ("0110", 2, false), + ("00000000001011100", 3, true), + ("000011010111011001001111111001000100100100010100101100001101101101110001100100101111100111001001111001001010111010010101101001001110011100110101001001001000000110101001010011101100110110100010000", 7, false) + ]; + for (s, k, o) in tests { + let result = Solution::has_all_codes(s.to_string(),k); + println!("{s:?} with {k} is {result} should be {o}"); + } +} + +struct Solution; + +impl Solution { + pub fn has_all_codes(s: String, k: i32) -> bool { + // (00..=2_i32.pow(k as u32) -1).all(|x| s.contains(&format!("{x:00$b}", k as usize)))j + let mut m: u128 = 0; + let mut m = (0..) + for w in s.chars().collect::<Vec<_>>().windows(k as usize) { + m |= 1 << i32::from_str_radix(&w.iter().collect::<String>(), 2).unwrap(); + // println!("{m:b}"); + } + // println!("{m:b}"); + let h = 2_u128.pow(2_u32.pow(k as u32)) -1; + // println!("{h} {h:b}"); + m == h + } +} diff --git a/check-if-all-as-appears-before-all-bs/Cargo.toml b/check-if-all-as-appears-before-all-bs/Cargo.toml new file mode 100644 index 0000000..2442447 --- /dev/null +++ b/check-if-all-as-appears-before-all-bs/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "check-if-all-as-appears-before-all-bs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/check-if-all-as-appears-before-all-bs/src/main.rs b/check-if-all-as-appears-before-all-bs/src/main.rs new file mode 100644 index 0000000..72ee26b --- /dev/null +++ b/check-if-all-as-appears-before-all-bs/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn check_string(s: String) -> bool { + !s.chars().skip_while(|&x| x == 'a').any(|x| x == 'a') + } +} diff --git a/check-if-it-is-a-straight-line/Cargo.toml b/check-if-it-is-a-straight-line/Cargo.toml new file mode 100644 index 0000000..596a8f3 --- /dev/null +++ b/check-if-it-is-a-straight-line/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "check-if-it-is-a-straight-line" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/check-if-it-is-a-straight-line/src/main.rs b/check-if-it-is-a-straight-line/src/main.rs new file mode 100644 index 0000000..711e12e --- /dev/null +++ b/check-if-it-is-a-straight-line/src/main.rs @@ -0,0 +1,37 @@ +fn main() { + let tests = [ + (vec![[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]], true), + (vec![[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]], false), + (vec![[0,0],[0,1],[0,-1]], true) + ]; + + for test in tests { + println!("{:?} is {} should be {}", + test.0, + check_straight_line(test.0.iter().map(|c| c.to_vec()).collect()), + test.1); + } +} + +pub fn check_straight_line(coordinates: Vec<Vec<i32>>) -> bool { + let base = get_lin_fn(coordinates[0].clone(), coordinates[1].clone()); + println!("{:?} base", base); + for c in 1..coordinates.len() { + let lin_fn = get_lin_fn(coordinates[0].clone(), coordinates[c].clone()); + println!("{} {:?}", c, lin_fn); + if lin_fn != base { + return false; + } + } + return true; +} + +pub fn get_lin_fn(a: Vec<i32>, b: Vec<i32>) -> (f32, f32) { + let mx = b[0] - a[0]; + let my = b[1] - a[1]; + let m = my as f32/mx as f32; + let b = a[1] as f32 - m*a[0] as f32; + + return (m,b); +} + diff --git a/check-if-two-string-arrays-are-equivalent/Cargo.toml b/check-if-two-string-arrays-are-equivalent/Cargo.toml new file mode 100644 index 0000000..1eaa37a --- /dev/null +++ b/check-if-two-string-arrays-are-equivalent/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "check-if-two-string-arrays-are-equivalent" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/check-if-two-string-arrays-are-equivalent/src/main.rs b/check-if-two-string-arrays-are-equivalent/src/main.rs new file mode 100644 index 0000000..6143793 --- /dev/null +++ b/check-if-two-string-arrays-are-equivalent/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn array_strings_are_equal(word1: Vec<String>, word2: Vec<String>) -> bool { + //word1.iter_mut().reduce(|a, b| {a.push_str(b); a}).unwrap() == word2.iter_mut().reduce(|a, b| {a.push_str(b); a}).unwrap() + //word1.concat() == word2.concat() + word1.iter().flat_map(|x| x.chars()).eq(word2.iter().flat_map(|x| x.chars())) + } +} diff --git a/combination-sum-iv/Cargo.toml b/combination-sum-iv/Cargo.toml new file mode 100644 index 0000000..9eeae96 --- /dev/null +++ b/combination-sum-iv/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "combination-sum-iv" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/combination-sum-iv/src/main.rs b/combination-sum-iv/src/main.rs new file mode 100644 index 0000000..b0ee823 --- /dev/null +++ b/combination-sum-iv/src/main.rs @@ -0,0 +1,37 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec![1,2,3], 4, 7), + // (vec![9], 3, 0), + (vec![2,1,3], 35, 1_132_436_852), + // (vec![10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370,380,390,400,410,420,430,440,450,460,470,480,490,500,510,520,530,540,550,560,570,580,590,600,610,620,630,640,650,660,670,680,690,700,710,720,730,740,750,760,770,780,790,800,810,820,830,840,850,860,870,880,890,900,910,920,930,940,950,960,970,980,990,111], 999, 2) + ]; + + for test in tests { + println!("{:?} {} is {} should be {}", + test.0, test.1, + Solution::combination_sum4(test.0.clone(), test.1), + test.2 + ); + } +} +struct Solution {} + + +impl Solution { + pub fn combination_sum4(nums: Vec<i32>, target: i32) -> i32 { + let mut cache = vec![0; target as usize]; + Solution::combination_sum4_from(&nums, 0, target, &mut cache) + } + + pub fn combination_sum4_from(nums: &Vec<i32>, from: i32, target: i32, cache: &mut Vec<i32>) -> i32 { + if from > target {return 0}; + if from == target {return 1}; + if cache[from as usize] > 0 {return cache[from as usize];} + + let result = nums.iter().rev().map(|x| Solution::combination_sum4_from(&nums, from + x, target, cache)).sum(); + cache[from as usize] = result; + println!("{:?}", cache); + result + } +} diff --git a/concatenation-of-array/Cargo.toml b/concatenation-of-array/Cargo.toml new file mode 100644 index 0000000..de3b44e --- /dev/null +++ b/concatenation-of-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "concatenation-of-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/concatenation-of-array/src/main.rs b/concatenation-of-array/src/main.rs new file mode 100644 index 0000000..f08a58d --- /dev/null +++ b/concatenation-of-array/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn get_concatenation(nums: Vec<i32>) -> Vec<i32> { + let mut result = nums.clone(); + result.append(&mut nums.clone()); + result + } +} diff --git a/contains-duplicate/Cargo.toml b/contains-duplicate/Cargo.toml new file mode 100644 index 0000000..3fb9396 --- /dev/null +++ b/contains-duplicate/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "contains-duplicate" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/contains-duplicate/src/main.rs b/contains-duplicate/src/main.rs new file mode 100644 index 0000000..d067614 --- /dev/null +++ b/contains-duplicate/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn contains_duplicate(nums: Vec<i32>) -> bool { + nums.iter(). + } +} diff --git a/counting-bits/Cargo.toml b/counting-bits/Cargo.toml new file mode 100644 index 0000000..6354b0d --- /dev/null +++ b/counting-bits/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "counting-bits" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/counting-bits/src/main.rs b/counting-bits/src/main.rs new file mode 100644 index 0000000..1203594 --- /dev/null +++ b/counting-bits/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + let tests = [ + (2, vec![0,1,1]), + (5, vec![0,1,1,2,1,2]) + ]; + + for test in tests { + println!("{} is {:?} should be {:?}", test.0, count_bits(test.0), test.1); + } +} + +fn count_bits(n: i32) -> Vec<i32> { + let mut solution: Vec<i32> = Vec::new(); + for i in 0..=n { + let mut ones = 0; + for c in 0..32 { + ones += (1<<c & i != 0) as i32; + } + solution.push(ones); + } + + return solution; +} diff --git a/decrypt-string-from-alphabet-to-integer-mapping/Cargo.toml b/decrypt-string-from-alphabet-to-integer-mapping/Cargo.toml new file mode 100644 index 0000000..57030b0 --- /dev/null +++ b/decrypt-string-from-alphabet-to-integer-mapping/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "decrypt-string-from-alphabet-to-integer-mapping" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/decrypt-string-from-alphabet-to-integer-mapping/src/main.rs b/decrypt-string-from-alphabet-to-integer-mapping/src/main.rs new file mode 100644 index 0000000..b3ace31 --- /dev/null +++ b/decrypt-string-from-alphabet-to-integer-mapping/src/main.rs @@ -0,0 +1,22 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn freq_alphabets(mut s: String) -> String { + for i in 10..=26 { + let mut integer_str = i.to_string(); + integer_str.push_str("#"); + s = s.replace(&integer_str, &char::from_u32(96 + i).unwrap().to_string() ); + } + for i in 1..=9 { + let integer_str = i.to_string(); + s = s.replace(&integer_str, &char::from_u32(96 + i).unwrap().to_string() ); + } + let i = s.chars().rev(); + i.map(|x| if x == '#' {i.take()}) + s + } +} diff --git a/design-hashmap/Cargo.toml b/design-hashmap/Cargo.toml new file mode 100644 index 0000000..5f27b3e --- /dev/null +++ b/design-hashmap/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "design-hashmap" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/design-hashmap/src/main.rs b/design-hashmap/src/main.rs new file mode 100644 index 0000000..f35bd69 --- /dev/null +++ b/design-hashmap/src/main.rs @@ -0,0 +1,43 @@ +fn main() { + println!("Hello, world!"); + let mut a = MyHashMap::new(); + a.put(1,1); + a.put(2,2); + a.get(1); + a.get(3); + a.put(2,1); + a.get(2); + a.remove(2); + a.get(2); +} + +struct MyHashMap { + map: Vec<(i32,i32)> +} + +impl MyHashMap { + + fn new() -> Self { + MyHashMap { + map: Vec::new() + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.map.iter_mut().find(|x| x.0 == key) { + Some(e) => e.1 = value, + None => self.map.push((key, value)) + }; + } + + fn get(&self, key: i32) -> i32 { + self.map.iter().find(|&x| x.0 == key).map(|x| x.1).unwrap_or(-1) + } + + fn remove(&mut self, key: i32) { + if let Some(e) = self.map.iter().position(|x| x.0 == key) { + self.map.swap_remove(e); + } + } +} + diff --git a/diagonal-traverse/Cargo.toml b/diagonal-traverse/Cargo.toml new file mode 100644 index 0000000..331f384 --- /dev/null +++ b/diagonal-traverse/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "diagonal-traverse" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/diagonal-traverse/src/main.rs b/diagonal-traverse/src/main.rs new file mode 100644 index 0000000..65f680b --- /dev/null +++ b/diagonal-traverse/src/main.rs @@ -0,0 +1,16 @@ +struct Solution; +impl Solution { + pub fn find_diagonal_order(mat: Vec<Vec<i32>>) -> Vec<i32> { + let mut solution: Vec<i32> = Vec::new(); + let x: usize = 0; + let y: usize = 0; + + solution.push(mat[x][y]); + + solution + } +} + +fn main() { + println!("Hello, world!"); +} diff --git a/extra-characters-in-a-string/Cargo.toml b/extra-characters-in-a-string/Cargo.toml new file mode 100644 index 0000000..7f2bfde --- /dev/null +++ b/extra-characters-in-a-string/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "extra-characters-in-a-string" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/extra-characters-in-a-string/src/main.rs b/extra-characters-in-a-string/src/main.rs new file mode 100644 index 0000000..f803964 --- /dev/null +++ b/extra-characters-in-a-string/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + let tests = vec![ + ("leetscode", vec!["leet","code","leetcode"], 1), + ("sayhelloworld", vec!["hello","world"], 3), + ]; + + for test in tests { + let result = min_extra_char( + test.0.to_string(), + test.1.iter().map(|s| s.to_string()).collect() + ); + println!("{} has {} should be {}", test.0, result, test.2); + } +} + +fn min_extra_char(s: String, dictionary: Vec<String>) -> i32 { + for i in 0..s.len() { + for w in dictionary { + s.starts_with(w); + } + } + 1 +} diff --git a/find-all-lonely-numbers-in-the-array/Cargo.toml b/find-all-lonely-numbers-in-the-array/Cargo.toml new file mode 100644 index 0000000..38ec185 --- /dev/null +++ b/find-all-lonely-numbers-in-the-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-all-lonely-numbers-in-the-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-all-lonely-numbers-in-the-array/src/main.rs b/find-all-lonely-numbers-in-the-array/src/main.rs new file mode 100644 index 0000000..1f1e6f9 --- /dev/null +++ b/find-all-lonely-numbers-in-the-array/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn find_lonely(mut nums: Vec<i32>) -> Vec<i32> { + if nums.len() == 1 {return nums;} + + nums.sort(); + + let mut result: Vec<i32> = nums.windows(3).filter(|arr| (arr[0] - arr[1]).abs() > 1).flat_map(|arr| Vec::from(arr)).collect(); + result.dedup(); + result + } +} diff --git a/find-first-palindromic-string-in-the-array/Cargo.toml b/find-first-palindromic-string-in-the-array/Cargo.toml new file mode 100644 index 0000000..25fc001 --- /dev/null +++ b/find-first-palindromic-string-in-the-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-first-palindromic-string-in-the-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-first-palindromic-string-in-the-array/src/main.rs b/find-first-palindromic-string-in-the-array/src/main.rs new file mode 100644 index 0000000..cf3d386 --- /dev/null +++ b/find-first-palindromic-string-in-the-array/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn first_palindrome(words: Vec<String>) -> String { + words.iter().find(|&s| s.chars().take(s.len() / 2).eq(s.chars().rev().take(s.len() / 2))).map(|x| x.clone()).unwrap_or(String::new()) + } +} diff --git a/find-in-mountain-array/Cargo.toml b/find-in-mountain-array/Cargo.toml new file mode 100644 index 0000000..e29d001 --- /dev/null +++ b/find-in-mountain-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-in-mountain-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-in-mountain-array/src/main.rs b/find-in-mountain-array/src/main.rs new file mode 100644 index 0000000..4fd6d7c --- /dev/null +++ b/find-in-mountain-array/src/main.rs @@ -0,0 +1,28 @@ +fn main() { + println!("Hello, world!"); +} +/** + * // This is the MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * struct MountainArray; + * impl MountainArray { + * fn get(index:i32)->i32; + * fn length()->i32; + * }; + */ + +struct MountainArray; + +impl MountainArray { + fn get(self, index:i32)->i32; + fn length(self)->i32; +}; + +impl Solution { + pub fn find_in_mountain_array(target: i32, mountainArr: &MountainArray) -> i32 { + for i in 0..mountainArr.length() { + if mountainArr.get(i) == target {return i;} + } + -1 + } +} diff --git a/find-smallest-letter-greater-than-target/Cargo.toml b/find-smallest-letter-greater-than-target/Cargo.toml new file mode 100644 index 0000000..f5086d4 --- /dev/null +++ b/find-smallest-letter-greater-than-target/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-smallest-letter-greater-than-target" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-smallest-letter-greater-than-target/src/main.rs b/find-smallest-letter-greater-than-target/src/main.rs new file mode 100644 index 0000000..aa9944c --- /dev/null +++ b/find-smallest-letter-greater-than-target/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + +pub fn next_greatest_letter(letters: Vec<char>, target: char) -> char { + let mut smallest: char = '~'; + let first = letters[0]; + + for c in letters { + if c > target && c < smallest {smallest = c;} + } + if smallest == '~' { + return first; + } + + return smallest; +} diff --git a/find-the-difference-of-two-arrays/Cargo.toml b/find-the-difference-of-two-arrays/Cargo.toml new file mode 100644 index 0000000..d44a464 --- /dev/null +++ b/find-the-difference-of-two-arrays/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "find-the-difference-of-two-arrays" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +itertools = "0.9.0" diff --git a/find-the-difference-of-two-arrays/src/main.rs b/find-the-difference-of-two-arrays/src/main.rs new file mode 100644 index 0000000..a09cecb --- /dev/null +++ b/find-the-difference-of-two-arrays/src/main.rs @@ -0,0 +1,25 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>> { + let mut a: Vec<i32> = Vec::new(); + let mut b: Vec<i32> = Vec::new(); + + for i in nums1 { + if !nums2.contains(&i) && !nums1.contains(&i) { + a.push(i); + } + } + for i in nums2 { + if !nums2.contains(&i) && !nums1.contains(&i) { + b.push(i); + } + } + + vec![a,b] + + } +} diff --git a/find-the-duplicate-number/Cargo.toml b/find-the-duplicate-number/Cargo.toml new file mode 100644 index 0000000..2f23362 --- /dev/null +++ b/find-the-duplicate-number/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-the-duplicate-number" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-the-duplicate-number/src/main.rs b/find-the-duplicate-number/src/main.rs new file mode 100644 index 0000000..c86c542 --- /dev/null +++ b/find-the-duplicate-number/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + + +struct Solution {} + +impl Solution { + pub fn find_duplicate(nums: Vec<i32>) -> i32 { + for i in 0..nums.len()-1 { + if nums[i+1..nums.len()].contains(&nums[i]) { + return nums[i]; + } + } + 0 + } +} diff --git a/find-the-highest-altitude/Cargo.toml b/find-the-highest-altitude/Cargo.toml new file mode 100644 index 0000000..648fce4 --- /dev/null +++ b/find-the-highest-altitude/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-the-highest-altitude" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-the-highest-altitude/src/main.rs b/find-the-highest-altitude/src/main.rs new file mode 100644 index 0000000..82fac4d --- /dev/null +++ b/find-the-highest-altitude/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn largest_altitude(gain: Vec<i32>) -> i32 { + let mut altitude = 0; + let mut result = 0; + for x in gain { + altitude += x; + result = result.max(altitude); + } + result + } +} diff --git a/find-the-index-of-the-first-occurrence-in-a-string/Cargo.toml b/find-the-index-of-the-first-occurrence-in-a-string/Cargo.toml new file mode 100644 index 0000000..0badc0f --- /dev/null +++ b/find-the-index-of-the-first-occurrence-in-a-string/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "find-the-index-of-the-first-occurrence-in-a-string" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/find-the-index-of-the-first-occurrence-in-a-string/src/main.rs b/find-the-index-of-the-first-occurrence-in-a-string/src/main.rs new file mode 100644 index 0000000..51de786 --- /dev/null +++ b/find-the-index-of-the-first-occurrence-in-a-string/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn str_str(haystack: String, needle: String) -> i32 { + match haystack.find(&needle) { + None => -1, + Some(e) => e as i32 + } + } +} diff --git a/fizz-buzz/Cargo.toml b/fizz-buzz/Cargo.toml new file mode 100644 index 0000000..0a2734e --- /dev/null +++ b/fizz-buzz/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "fizz-buzz" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/fizz-buzz/src/main.rs b/fizz-buzz/src/main.rs new file mode 100644 index 0000000..c6abf23 --- /dev/null +++ b/fizz-buzz/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + println!("Hello, world!"); +} + +impl Solution { + pub fn fizz_buzz(n: i32) -> Vec<String> { + (1..=n).map(|x| match x { + i if i % 3 == 0 && x % 5 == 0 => "FizzBuzz".to_string(), + i if i % 3 == 0 => "Fizz".to_string(), + i if i % 5 == 0 => "Buzz".to_string(), + i => i.to_string() + }).collect() + } +} diff --git a/group-the-people-given-the-group-size-they-belong-to/Cargo.toml b/group-the-people-given-the-group-size-they-belong-to/Cargo.toml new file mode 100644 index 0000000..5a9601f --- /dev/null +++ b/group-the-people-given-the-group-size-they-belong-to/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "group-the-people-given-the-group-size-they-belong-to" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/group-the-people-given-the-group-size-they-belong-to/src/main.rs b/group-the-people-given-the-group-size-they-belong-to/src/main.rs new file mode 100644 index 0000000..f380f39 --- /dev/null +++ b/group-the-people-given-the-group-size-they-belong-to/src/main.rs @@ -0,0 +1,26 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn group_the_people(group_sizes: Vec<i32>) -> Vec<Vec<i32>> { + let mut result: Vec<Vec<i32>> = Vec::new(); + + + for (i, size) in group_sizes.iter().enumerate() { + let group = result.iter_mut() + .find(|x| x.capacity() == *size as usize && x.len() != x.capacity()); + + match group { + Some(entry) => entry.push(i as i32), + None => { + let mut new_group = Vec::with_capacity(*size as usize); + new_group.push(i as i32); + result.push(new_group); + } + }; + } + result + } +} diff --git a/increasing-order-search-tree/Cargo.toml b/increasing-order-search-tree/Cargo.toml new file mode 100644 index 0000000..8dca9d6 --- /dev/null +++ b/increasing-order-search-tree/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "increasing-order-search-tree" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/increasing-order-search-tree/src/main.rs b/increasing-order-search-tree/src/main.rs new file mode 100644 index 0000000..8953101 --- /dev/null +++ b/increasing-order-search-tree/src/main.rs @@ -0,0 +1,33 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} + +// Definition for a binary tree node. +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option<Rc<RefCell<TreeNode>>>, + pub right: Option<Rc<RefCell<TreeNode>>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: i32) -> Self { + TreeNode { + val, + left: None, + right: None + } + } +} +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn increasing_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { + match root.unwrap().get_mut() { + TreeNode { val, left: None, right: None } => {root} + } + } +} diff --git a/k-th-symbol-in-grammar/Cargo.toml b/k-th-symbol-in-grammar/Cargo.toml new file mode 100644 index 0000000..4fccf4e --- /dev/null +++ b/k-th-symbol-in-grammar/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "k-th-symbol-in-grammar" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/k-th-symbol-in-grammar/src/main.rs b/k-th-symbol-in-grammar/src/main.rs new file mode 100644 index 0000000..5aaa24c --- /dev/null +++ b/k-th-symbol-in-grammar/src/main.rs @@ -0,0 +1,28 @@ +fn main() { + println!("Hello, world!"); + let tests = vec![ + (1,1,0), + (2,1,0), + (2,2,1), + (30, 434991989, 0) + ]; + for (n,k,o) in tests { + let result = Solution::kth_grammar(n,k); + println!("{n} {k} {result} {o}"); + } +} + +struct Solution; + +impl Solution { + pub fn kth_grammar(n: i32, k: i32) -> i32 { + let mut s: Vec<bool> = vec![false]; + for _ in 0..n { + s = s.iter().flat_map(|x| match x { + false => [false,true], + true => [true,false] + }).collect::<Vec<_>>(); + } + s[(k - 1) as usize] as i32 + } +} diff --git a/kth-largest-element-in-a-stream/Cargo.toml b/kth-largest-element-in-a-stream/Cargo.toml new file mode 100644 index 0000000..b9f7f80 --- /dev/null +++ b/kth-largest-element-in-a-stream/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "kth-largest-element-in-a-stream" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/kth-largest-element-in-a-stream/src/main.rs b/kth-largest-element-in-a-stream/src/main.rs new file mode 100644 index 0000000..1a3d3ff --- /dev/null +++ b/kth-largest-element-in-a-stream/src/main.rs @@ -0,0 +1,30 @@ +fn main() { + println!("Hello, world!"); +} + + +struct KthLargest { + +} + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl KthLargest { + + fn new(k: i32, nums: Vec<i32>) -> Self { + + } + + fn add(&self, val: i32) -> i32 { + + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * let obj = KthLargest::new(k, nums); + * let ret_1: i32 = obj.add(val); + */ diff --git a/length-of-last-word/Cargo.toml b/length-of-last-word/Cargo.toml new file mode 100644 index 0000000..299ca49 --- /dev/null +++ b/length-of-last-word/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "length-of-last-word" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/length-of-last-word/src/main.rs b/length-of-last-word/src/main.rs new file mode 100644 index 0000000..d3e51ff --- /dev/null +++ b/length-of-last-word/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn length_of_last_word(s: String) -> i32 { + s.split_whitespace().last().unwrap().len() as i32 + } +} diff --git a/longest-common-prefix/Cargo.toml b/longest-common-prefix/Cargo.toml new file mode 100644 index 0000000..91d0dc9 --- /dev/null +++ b/longest-common-prefix/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "longest-common-prefix" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/longest-common-prefix/src/main.rs b/longest-common-prefix/src/main.rs new file mode 100644 index 0000000..9e573c1 --- /dev/null +++ b/longest-common-prefix/src/main.rs @@ -0,0 +1,30 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec!["flower","flow","flight"], "fl"), + (vec!["dog","racecar","car"], "") + ]; + + for test in tests { + println!("{:?} is {} should be {}", test.0, + Solution::longest_common_prefix(test.0.iter().map(|s| s.to_string()).collect()), + test.1); + } +} + +struct Solution {} +impl Solution { + pub fn longest_common_prefix(strs: Vec<String>) -> String { + let mut index = 0; + let mut c = String::new(); + loop { + for s in strs { + let prefix = s.chars().nth(index); + if prefix.is_none() {return c;} + } + break; + } + "".to_string() + } +} + diff --git a/majority-element-ii/Cargo.toml b/majority-element-ii/Cargo.toml new file mode 100644 index 0000000..71a2fbe --- /dev/null +++ b/majority-element-ii/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "majority-element-ii" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/majority-element-ii/src/main.rs b/majority-element-ii/src/main.rs new file mode 100644 index 0000000..34872a4 --- /dev/null +++ b/majority-element-ii/src/main.rs @@ -0,0 +1,28 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + vec![3,2,3], + vec![1], + vec![1,2] + ]; + + for test in tests { + let result = Solution::majority_element(test.clone()); + println!("{test:?} is {result:?}"); + } +} + +struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn majority_element(nums: Vec<i32>) -> Vec<i32> { + let mut occurance: HashMap<&i32, i32> = HashMap::new(); + + for num in &nums { + occurance.entry(num).and_modify(|x| {*x += 1}).or_insert(0); + } + occurance.iter().filter(|(_, &occ)| occ >= nums.len() as i32 / 3).map(|(&&num,_)| num).collect() + } +} diff --git a/majority-element/Cargo.toml b/majority-element/Cargo.toml new file mode 100644 index 0000000..8930310 --- /dev/null +++ b/majority-element/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "majority-element" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/majority-element/src/main.rs b/majority-element/src/main.rs new file mode 100644 index 0000000..f6757e0 --- /dev/null +++ b/majority-element/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn majority_element(nums: Vec<i32>) -> i32 { + let mut table = HashMap::new(); + + for num in nums { + *table.entry(num).or_insert(1) += 1; + } + + *table.iter().reduce(|a,b| if a.1 > b.1 {a} else {b}).unwrap().0 + } +} diff --git a/matrix-diagonal-sum/Cargo.toml b/matrix-diagonal-sum/Cargo.toml new file mode 100644 index 0000000..b0abc38 --- /dev/null +++ b/matrix-diagonal-sum/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "matrix-diagonal-sum" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/matrix-diagonal-sum/src/main.rs b/matrix-diagonal-sum/src/main.rs new file mode 100644 index 0000000..8ee95a0 --- /dev/null +++ b/matrix-diagonal-sum/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32 { + mat.iter().enumerate() + .fold(0, |acc, (i, row)| acc + row[i] + if i != row.len()-1 -i {row[row.len()-1 -i]} else {0}) + } +} diff --git a/median-of-two-sorted-arrays/Cargo.toml b/median-of-two-sorted-arrays/Cargo.toml new file mode 100644 index 0000000..58b9f7b --- /dev/null +++ b/median-of-two-sorted-arrays/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "median-of-two-sorted-arrays" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/median-of-two-sorted-arrays/src/main.rs b/median-of-two-sorted-arrays/src/main.rs new file mode 100644 index 0000000..a8557aa --- /dev/null +++ b/median-of-two-sorted-arrays/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + println!("Hello, world!"); + let tests = vec![ + (vec![1,3], vec![2], 2.0), + (vec![1,2], vec![3,4], 2.5) + ]; + for test in tests { + println!("{:?}{:?} is {} should be {}", test.0, test.1, + Solution::find_median_sorted_arrays(test.0.clone(), test.1.clone()), test.2); + } +} + +struct Solution {} +impl Solution { + pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 { + let mut a = nums1.clone(); + a.append(&mut nums2.clone()); + a.sort(); + let median = a.get((a.len() / 2)-1..((a.len() + 1)/2)).unwrap(); + println!("{:?}", median); + (median.iter().sum::<i32>() as f64) / (median.len() as f64) + } +} diff --git a/minimum-changes-to-make-alternating-binary-string/Cargo.toml b/minimum-changes-to-make-alternating-binary-string/Cargo.toml new file mode 100644 index 0000000..01c4446 --- /dev/null +++ b/minimum-changes-to-make-alternating-binary-string/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minimum-changes-to-make-alternating-binary-string" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/minimum-changes-to-make-alternating-binary-string/src/main.rs b/minimum-changes-to-make-alternating-binary-string/src/main.rs new file mode 100644 index 0000000..369635d --- /dev/null +++ b/minimum-changes-to-make-alternating-binary-string/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn min_operations(s: String) -> i32 { + let a: Vec<_> = s.chars().collect(); + i32::min( + a.chunks(2).map(|x| match x { ['0','1'] | ['0'] => 0, ['1', '0'] => 2, _ => 1 }).sum(), + a.chunks(2).map(|x| match x { ['1','0'] | ['1'] => 0, ['0', '1'] => 2, _ => 1 }).sum() + ) + } +} diff --git a/minimum-deletions-to-make-character-frequencies-unique/Cargo.toml b/minimum-deletions-to-make-character-frequencies-unique/Cargo.toml new file mode 100644 index 0000000..d098b5a --- /dev/null +++ b/minimum-deletions-to-make-character-frequencies-unique/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minimum-deletions-to-make-character-frequencies-unique" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/minimum-deletions-to-make-character-frequencies-unique/src/main.rs b/minimum-deletions-to-make-character-frequencies-unique/src/main.rs new file mode 100644 index 0000000..1ca58f3 --- /dev/null +++ b/minimum-deletions-to-make-character-frequencies-unique/src/main.rs @@ -0,0 +1,79 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("aab", 0), + ("aaabbbcc", 2), + ("ceabaacb", 2), + ("accdcdadddbaadbc", 1), + ("abcabc", 3), + ("bbcebab",2) + ]; + + for test in tests { + println!("{:?} is {} should be {}", + test.0, + Solution::min_deletions(test.0.to_string()), + test.1 + ); + } +} + + +struct Solution {} + +use std::collections::HashMap; + +impl Solution { + pub fn min_deletions(s: String) -> i32 { + // aaabbbcc => a: 3, b: 3, c: 2 + let mut char_occurance = HashMap::new(); + + for c in s.chars() { + char_occurance.entry(c).and_modify(|x| *x += 1).or_insert(1); + } + + // 2, 3, 3 + let mut occurences: Vec<i32> = char_occurance.values().cloned().collect(); + occurences.sort(); + + // 2: 1, 3: 2 + let mut occurence_occurences = HashMap::new(); + // println!("{:?}", occurences); + for i in occurences { + occurence_occurences.entry(i).and_modify(|x| *x += 1).or_insert(1); + } + + let a = occurence_occurences.iter().collect::<Vec<_>>(); + // println!("{:?}", a); + + // 3 + let mut needs_change = Vec::new(); + for (key, val) in occurence_occurences.iter() { + if *val > 1 { + needs_change.push(*key); + } + } + + let mut changes = 0; + for key in needs_change.iter() { + let mut val = occurence_occurences.get(&key).unwrap().clone(); + while val > 1 { + for i in (0..*key).rev() { + let occ = occurence_occurences.get(&i); + if occ.is_none() { + val += -1; + changes += key - i; + if i > 0 { + occurence_occurences.insert(i, key-i); + } + break; + } + } + } + + } + // println!("{occurence_occurences:?}"); + changes + } +} + diff --git a/minimum-operations-to-reduce-x-to-zero/Cargo.toml b/minimum-operations-to-reduce-x-to-zero/Cargo.toml new file mode 100644 index 0000000..0630adf --- /dev/null +++ b/minimum-operations-to-reduce-x-to-zero/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minimum-operations-to-reduce-x-to-zero" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/minimum-operations-to-reduce-x-to-zero/src/main.rs b/minimum-operations-to-reduce-x-to-zero/src/main.rs new file mode 100644 index 0000000..55ee894 --- /dev/null +++ b/minimum-operations-to-reduce-x-to-zero/src/main.rs @@ -0,0 +1,39 @@ +use std::cmp::min; + + +struct Solution; +impl Solution { + pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 { + Self::min_operations_slice(&nums[..], x) + } + + pub fn min_operations_slice(nums: &[i32], x: i32) -> i32 { + if x == 0 {return 0;} + if x < 0 || nums.is_empty() {return -1;} + + match ( + Self::min_operations_slice(&nums[..nums.len() - 1], x - &nums[nums.len() - 1]), + Self::min_operations_slice(&nums[1..], x - &nums[0]) + ) { + (-1, -1) => -1, + (x,-1) | (-1, x) => x+1, + (x, y) => min(x,y)+1, + } + } +} + +fn main() { + + let tests = vec![ + (vec![1,1,4,2,3], 5, 2), + (vec![5,6,7,8,9], 4, -1), + (vec![3,2,20,1,1,3], 10, 5), + (vec![1,1], 3, -1), + (vec![1241,8769,9151,3211,2314,8007,3713,5835,2176,8227,5251,9229,904,1899,5513,7878,8663,3804,2685,3501,1204,9742,2578,8849,1120,4687,5902,9929,6769,8171,5150,1343,9619,3973,3273,6427,47,8701,2741,7402,1412,2223,8152,805,6726,9128,2794,7137,6725,4279,7200,5582,9583,7443,6573,7221,1423,4859,2608,3772,7437,2581,975,3893,9172,3,3113,2978,9300,6029,4958,229,4630,653,1421,5512,5392,7287,8643,4495,2640,8047,7268,3878,6010,8070,7560,8931,76,6502,5952,4871,5986,4935,3015,8263,7497,8153,384,1136], 894887480, 0) + ]; + + for (nums, x, out) in tests { + let result = Solution::min_operations(nums.clone(), x); + println!("{nums:?} {x} is {result} should be {out}"); + } +} diff --git a/minimum-operations-to-reduce-x-to-zero/src/main2.rs b/minimum-operations-to-reduce-x-to-zero/src/main2.rs new file mode 100644 index 0000000..1ab02ab --- /dev/null +++ b/minimum-operations-to-reduce-x-to-zero/src/main2.rs @@ -0,0 +1,38 @@ +use std::cmp::min; + +struct Solution; +impl Solution { + pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 { + Self::min_operations_slice(&nums[..], x).unwrap_or(-1) + } + + pub fn min_operations_slice(nums: &[i32], x: i32) -> Option<i32> { + if x < 0 || nums.is_empty() {return None;} + if x == 0 {return Some(0);} + + match ( + Self::min_operations_slice(&nums[..nums.len() - 1], x - &nums[nums.len() - 1]), + Self::min_operations_slice(&nums[1..], x - &nums[0]) + ) { + (None, None) => None, + (Some(x), Some(y)) => Some(min(x,y)+1), + (Some(x),None) | (None, Some(x)) => Some(x+1) + } + } +} + +fn main() { + + let tests = vec![ + (vec![1,1,4,2,3], 5, 2), + (vec![5,6,7,8,9], 4, -1), + (vec![3,2,20,1,1,3], 10, 5), + (vec![1,1], 3, -1), + (vec![1241,8769,9151,3211,2314,8007,3713,5835,2176,8227,5251,9229,904,1899,5513,7878,8663,3804,2685,3501,1204,9742,2578,8849,1120,4687,5902,9929,6769,8171,5150,1343,9619,3973,3273,6427,47,8701,2741,7402,1412,2223,8152,805,6726,9128,2794,7137,6725,4279,7200,5582,9583,7443,6573,7221,1423,4859,2608,3772,7437,2581,975,3893,9172,3,3113,2978,9300,6029,4958,229,4630,653,1421,5512,5392,7287,8643,4495,2640,8047,7268,3878,6010,8070,7560,8931,76,6502,5952,4871,5986,4935,3015,8263,7497,8153,384,1136], 894887480, 0) + ]; + + for (nums, x, out) in tests { + let result = Solution::min_operations(nums.clone(), x); + println!("{nums:?} {x} is {result} should be {out}"); + } +} diff --git a/monotonic-array/Cargo.toml b/monotonic-array/Cargo.toml new file mode 100644 index 0000000..d8244c5 --- /dev/null +++ b/monotonic-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "monotonic-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/monotonic-array/src/main.rs b/monotonic-array/src/main.rs new file mode 100644 index 0000000..eeb1b2e --- /dev/null +++ b/monotonic-array/src/main.rs @@ -0,0 +1,20 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec![1,2,2,3],true), + (vec![6,5,4,4],true), + (vec![1,3,2], false) + ]; + + for test in tests { + println!("{:?} is {} should be {}", test.0, Solution::is_monotonic(test.0.clone()), + test.1); + } +} +struct Solution; +impl Solution { + pub fn is_monotonic(nums: Vec<i32>) -> bool { + nums.windows(2).all(|x| x[0] >= x[1]) || + nums.windows(2).all(|x| x[0] <= x[1]) + } +} diff --git a/n-ary-tree-postorder-traversal/Cargo.toml b/n-ary-tree-postorder-traversal/Cargo.toml new file mode 100644 index 0000000..b7cc953 --- /dev/null +++ b/n-ary-tree-postorder-traversal/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "n-ary-tree-postorder-traversal" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/n-ary-tree-postorder-traversal/src/main.rs b/n-ary-tree-postorder-traversal/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/n-ary-tree-postorder-traversal/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/next-greater-element-i/Cargo.toml b/next-greater-element-i/Cargo.toml new file mode 100644 index 0000000..406d4ef --- /dev/null +++ b/next-greater-element-i/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "next-greater-element-i" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/next-greater-element-i/src/main.rs b/next-greater-element-i/src/main.rs new file mode 100644 index 0000000..84ab40c --- /dev/null +++ b/next-greater-element-i/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} + +impl Solution { + pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { + let mut result = nums1.clone(); + for i in result.iter_mut() { + nums2.iter().position(|&x| x == *i); + } + + + result + } +} diff --git a/number-of-different-integers-in-a-string/Cargo.toml b/number-of-different-integers-in-a-string/Cargo.toml new file mode 100644 index 0000000..aca88ce --- /dev/null +++ b/number-of-different-integers-in-a-string/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "number-of-different-integers-in-a-string" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/number-of-different-integers-in-a-string/src/main.rs b/number-of-different-integers-in-a-string/src/main.rs new file mode 100644 index 0000000..5a8256e --- /dev/null +++ b/number-of-different-integers-in-a-string/src/main.rs @@ -0,0 +1,29 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("a123bc34d8ef34", 3), + ("leet1234code234", 2), + ("a1b01c001", 1), + ("035985750011523523129774573439111590559325a1554234973", 2) + ]; + for test in tests { + println!("{:?} is {} should be {}", test.0, + Solution::num_different_integers(test.0.to_string()), test.1); + } +} + +struct Solution; + +use std::collections::HashSet; + +impl Solution { + pub fn num_different_integers(word: String) -> i32 { + let result = unsafe { word.as_bytes() }.split(u8::is_ascii_alphabetic) + .filter(|x| !x.is_empty()) + .map(|mut x| {while x.starts_with(b"0") {x = x.strip_prefix(b"0").unwrap(); } x}) + // .map(|x| x.iter().rev().enumerate().fold(0, |acc, (i,&v)| acc + (v as u32 -48) * 10_u32.pow(i as u32))) + .collect::<HashSet<&[u8]>>(); + println!("{result:?}"); + result.len() as i32 + } +} diff --git a/number-of-equivalent-domino-pairs/Cargo.toml b/number-of-equivalent-domino-pairs/Cargo.toml new file mode 100644 index 0000000..b0cfcd7 --- /dev/null +++ b/number-of-equivalent-domino-pairs/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "number-of-equivalent-domino-pairs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/number-of-equivalent-domino-pairs/src/main.rs b/number-of-equivalent-domino-pairs/src/main.rs new file mode 100644 index 0000000..ff16907 --- /dev/null +++ b/number-of-equivalent-domino-pairs/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn num_equiv_domino_pairs(dominoes: Vec<Vec<i32>>) -> i32 { + let mut map = [0;100]; + for d in dominoes { + if let [i,j] = d[..] { + map[(i.max(j) * 10 + i.min(j)) as usize] += 1; + } + } + map.iter().filter(|&&x| x > 1).map(|&x| (x *(x-1))/2).sum::<i32>() + } +} diff --git a/palindrome-number/Cargo.toml b/palindrome-number/Cargo.toml new file mode 100644 index 0000000..dd3c2d3 --- /dev/null +++ b/palindrome-number/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "palindrome-number" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/palindrome-number/src/main.rs b/palindrome-number/src/main.rs new file mode 100644 index 0000000..1e0d6d1 --- /dev/null +++ b/palindrome-number/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (121, true), + (-121, false), + (10, false), + (1410110141, true) + ]; + for test in tests { + println!("{} is {} should be {}", test.0, Solution::is_palindrome(test.0), test.1); + } +} + + +struct Solution {} +impl Solution { + pub fn is_palindrome(x: i32) -> bool { + if x < 0 {return false;} + let len = (x as f32).log10() as usize; + //println!("{} {}", len, (len+1)/2); + for i in 0..(len+1)/2 { + if (x as u32 / 10_u32.pow(i as u32)) % 10 != (x as u32 / 10_u32.pow((len - i) as u32)) % 10 { + return false; + } + } + true + } + pub fn get(x: i32, i: usize) -> u32 { + (x as u32 / 10_u32.pow(i as u32)) % 10 + } +} diff --git a/pascals-triangle/Cargo.toml b/pascals-triangle/Cargo.toml new file mode 100644 index 0000000..99cb41f --- /dev/null +++ b/pascals-triangle/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "pascals-triangle" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/pascals-triangle/src/main.rs b/pascals-triangle/src/main.rs new file mode 100644 index 0000000..7755650 --- /dev/null +++ b/pascals-triangle/src/main.rs @@ -0,0 +1,32 @@ +fn main() { + println!("Hello, world!"); + let tests = vec![ + (5, vec![ + vec![1],vec![1,1],vec![1,2,1],vec![1,3,3,1],vec![1,4,6,4,1] + ]), + (1, vec![vec![1]]) + ]; + + for test in tests { + println!("{} is {:?} should be {:?}", test.0, Solution::generate(test.0), test.1); + } +} + +struct Solution {} +impl Solution { + pub fn generate(num_rows: i32) -> Vec<Vec<i32>> { + let mut rows = Vec::with_capacity(num_rows as usize); + rows.push(vec![1]); + for i in 1..num_rows { + let mut row: Vec<i32> = Vec::with_capacity((i+1) as usize); + for ii in 0..=i { + let above = &rows[(i-1) as usize]; + row.push(if ii == 0 || i == ii {1} else {above[(ii-1) as usize] + above[ii as usize]}); + } + rows.push(row); + } + + rows + } +} + diff --git a/plus-one/Cargo.toml b/plus-one/Cargo.toml new file mode 100644 index 0000000..d912d93 --- /dev/null +++ b/plus-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "plus-one" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/plus-one/src/main.rs b/plus-one/src/main.rs new file mode 100644 index 0000000..7fdef54 --- /dev/null +++ b/plus-one/src/main.rs @@ -0,0 +1,21 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn plus_one(digits: Vec<i32>) -> Vec<i32> { + let mut result = Vec::with_capacity(digits.len()+1); + let mut carry = 1; + for i in digits.iter().rev() { + let sum = *i + carry; + result.push(sum % 10); + carry = sum / 10; + } + if carry > 0 { + result.push(carry); + } + result.reverse(); + result + } +} diff --git a/remove-all-occurrences-of-a-substring/Cargo.toml b/remove-all-occurrences-of-a-substring/Cargo.toml new file mode 100644 index 0000000..d872dcc --- /dev/null +++ b/remove-all-occurrences-of-a-substring/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-all-occurrences-of-a-substring" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-all-occurrences-of-a-substring/src/main.rs b/remove-all-occurrences-of-a-substring/src/main.rs new file mode 100644 index 0000000..8e1e181 --- /dev/null +++ b/remove-all-occurrences-of-a-substring/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn remove_occurrences(mut s: String, part: String) -> String { + while s.contains(&part) { + s = s.replacen(&part, "", 1); + } + s + } +} diff --git a/remove-colored-pieces-if-both-neighbors-are-the-same-color/Cargo.toml b/remove-colored-pieces-if-both-neighbors-are-the-same-color/Cargo.toml new file mode 100644 index 0000000..30239ca --- /dev/null +++ b/remove-colored-pieces-if-both-neighbors-are-the-same-color/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-colored-pieces-if-both-neighbors-are-the-same-color" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-colored-pieces-if-both-neighbors-are-the-same-color/src/main.rs b/remove-colored-pieces-if-both-neighbors-are-the-same-color/src/main.rs new file mode 100644 index 0000000..298c43d --- /dev/null +++ b/remove-colored-pieces-if-both-neighbors-are-the-same-color/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("AAABABB", true), + ("AA", false), + ("ABBBBBBBAAA", false), + ("AAAABBBB", false) + ]; + for (input, output) in tests { + let result = Solution::winner_of_game(input.to_string()); + println!("{input:?} is {result} should be {output:?}"); + } +} + +struct Solution; + +impl Solution { + pub fn winner_of_game(mut colors: String) -> bool { + if colors.len() < 3 {return false;} + let mut is_alice_turn = true; + while ((is_alice_turn && colors.contains("AAA")) || (!is_alice_turn) && colors.contains("BBB")) { + if is_alice_turn { + colors = colors.replacen("AAA", "AA", 1); + } else { + colors = colors.replacen("BBB", "BB", 1); + } + is_alice_turn = !is_alice_turn + } + !is_alice_turn + } +} diff --git a/remove-duplicate-letters/Cargo.toml b/remove-duplicate-letters/Cargo.toml new file mode 100644 index 0000000..65fc799 --- /dev/null +++ b/remove-duplicate-letters/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-duplicate-letters" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-duplicate-letters/src/main.rs b/remove-duplicate-letters/src/main.rs new file mode 100644 index 0000000..9cc7296 --- /dev/null +++ b/remove-duplicate-letters/src/main.rs @@ -0,0 +1,27 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("bcabc", "abc"), + ("cbacdcbc", "acdb") + ]; + + for test in tests { + println!("{:?} is {:?} should be {:?}", test.0, + Solution::remove_duplicate_letters(test.0.to_string()), test.1); + } +} + +struct Solution; + +impl Solution { + pub fn remove_duplicate_letters(s: String) -> String { + let mut a: Vec<char> = Vec::with_capacity(s.len()); + let start = s.chars().enumerate().reduce(|a,b| if a.1 < b.1 {a} else {b}); + for c in s.chars().skip(start.unwrap().0) { + if a.last().is_none() || c > *a.last().unwrap() { + a.push(c); + } + } + a.iter().collect::<String>() + } +} diff --git a/remove-duplicates-from-sorted-array/Cargo.toml b/remove-duplicates-from-sorted-array/Cargo.toml new file mode 100644 index 0000000..8d10bd5 --- /dev/null +++ b/remove-duplicates-from-sorted-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-duplicates-from-sorted-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-duplicates-from-sorted-array/src/main.rs b/remove-duplicates-from-sorted-array/src/main.rs new file mode 100644 index 0000000..2838a46 --- /dev/null +++ b/remove-duplicates-from-sorted-array/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 { + nums.dedup(); + nums.len() as i32 + } +} diff --git a/remove-element/Cargo.toml b/remove-element/Cargo.toml new file mode 100644 index 0000000..c4f2338 --- /dev/null +++ b/remove-element/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-element" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-element/src/main.rs b/remove-element/src/main.rs new file mode 100644 index 0000000..807cd97 --- /dev/null +++ b/remove-element/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 { + let elements: Vec<_> = nums.iter().enumerate().filter(|(_,&num)| num == val).map(|(i,_)| i).collect(); + for i in &elements { + nums.remove(*i); + } + elements.len() as i32 + } +} diff --git a/remove-one-element-to-make-the-array-strictly-increasing/Cargo.toml b/remove-one-element-to-make-the-array-strictly-increasing/Cargo.toml new file mode 100644 index 0000000..ccf1b7c --- /dev/null +++ b/remove-one-element-to-make-the-array-strictly-increasing/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove-one-element-to-make-the-array-strictly-increasing" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove-one-element-to-make-the-array-strictly-increasing/src/main.rs b/remove-one-element-to-make-the-array-strictly-increasing/src/main.rs new file mode 100644 index 0000000..d9f5304 --- /dev/null +++ b/remove-one-element-to-make-the-array-strictly-increasing/src/main.rs @@ -0,0 +1,20 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec![1,2,10,5,7], true), + (vec![2,3,1,2], false), + (vec![1,1,1], false) + ]; + for test in tests { + println!("{:?} is {} should be {}", test.0, Solution::can_be_increasing(test.0.clone()), + test.1); + } +} + +struct Solution; + +impl Solution { + pub fn can_be_increasing(nums: Vec<i32>) -> bool { + nums.windows(2).filter(|x| x[0] < x[1]).count() + 2 == nums.len() + } +} diff --git a/replace-all-digits-with-characters/Cargo.toml b/replace-all-digits-with-characters/Cargo.toml new file mode 100644 index 0000000..ec8606e --- /dev/null +++ b/replace-all-digits-with-characters/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "replace-all-digits-with-characters" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/replace-all-digits-with-characters/src/main.rs b/replace-all-digits-with-characters/src/main.rs new file mode 100644 index 0000000..881d15a --- /dev/null +++ b/replace-all-digits-with-characters/src/main.rs @@ -0,0 +1,20 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("a1c1e1", "abcdef"), + ("a1b2c3d4e", "abbdcfdhe") + ]; + for (input, output) in tests { + let result = Solution::replace_digits(input.to_string()); + println!("{input:?} is {result:?} should be {output:?}"); + } +} + +struct Solution; + +impl Solution { + pub fn replace_digits(mut s: String) -> String { + unsafe {s.as_bytes_mut()}.chunks_exact_mut(2).for_each(|x| x[1] = x[0] + x[1] - b'0'); + s + } +} diff --git a/reverse-integer/Cargo.toml b/reverse-integer/Cargo.toml new file mode 100644 index 0000000..c6ea71f --- /dev/null +++ b/reverse-integer/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "reverse-integer" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/reverse-integer/src/main.rs b/reverse-integer/src/main.rs new file mode 100644 index 0000000..acb54a6 --- /dev/null +++ b/reverse-integer/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + println!("Hello, world!"); +} + + +struct Solution; + +impl Solution { + pub fn reverse(x: i32) -> i32 { + x.abs().to_string().chars().rev().collect::<String>().parse::<i32>().unwrap_or(0) * x.signum() + } +} diff --git a/reverse-linked-list-ii/Cargo.toml b/reverse-linked-list-ii/Cargo.toml new file mode 100644 index 0000000..d8764c6 --- /dev/null +++ b/reverse-linked-list-ii/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "reverse-linked-list-ii" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/reverse-linked-list-ii/src/main.rs b/reverse-linked-list-ii/src/main.rs new file mode 100644 index 0000000..20790aa --- /dev/null +++ b/reverse-linked-list-ii/src/main.rs @@ -0,0 +1,59 @@ +fn main() { + let tests = [ + (vec![1,2,3,4,5], 2, 4, vec![1,4,3,2,5]), + (vec![5], 1, 1, vec![5]) + ]; + + for test in tests { + let a = ListNode::new_from_vec(test.0.clone()); + println!("{:?} is {:?} should be {:?}", test.0, Solution::reverse_between(a, test.1, test.2).unwrap().to_vec(), test.3); + } + +} + +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option<Box<ListNode>> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} + +impl ListNode { + fn new_from_vec(val: Vec<i32>) -> Option<Box<Self>> { + let mut first = ListNode::new(val[0]); + if val.len() > 1 { + let slice = &val[1..val.len()]; + first.next = Self::new_from_vec(slice.to_vec()); + } + Some(Box::new(first)) + } + pub fn to_vec(&self) -> Vec<i32> { + let mut v = Vec::new(); + + let mut a = Some(Box::new(self.to_owned())); + while a.is_some() { + let t = a.unwrap(); + v.push(t.val); + a = t.next; + } + v + } +} +struct Solution {} +impl Solution { + pub fn reverse_between(head: Option<Box<ListNode>>, left: i32, right: i32) -> Option<Box<ListNode>> { + let v = &mut head.unwrap().to_vec(); + v[((left-1) as usize)..(right as usize)].reverse(); + + ListNode::new_from_vec( v.to_vec() ) + } +} diff --git a/reverse-string-ii/Cargo.toml b/reverse-string-ii/Cargo.toml new file mode 100644 index 0000000..10128f6 --- /dev/null +++ b/reverse-string-ii/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "reverse-string-ii" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/reverse-string-ii/src/main.rs b/reverse-string-ii/src/main.rs new file mode 100644 index 0000000..883f24f --- /dev/null +++ b/reverse-string-ii/src/main.rs @@ -0,0 +1,21 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("abcdefg", 2, "bacdfeg"), + ("abcd", 2, "bacd") + ]; + + for test in tests { + println!("{:?} {} is {:?} should be {:?}", test.0, test.1, + Solution::reverse_str(test.0.to_string(), test.1), test.2); + } +} + +struct Solution; + +impl Solution { + pub fn reverse_str(mut s: String, k: i32) -> String { + unsafe { s.as_bytes_mut() }.chunks_mut(k as usize).step_by(2).for_each(|x| x.reverse()); + s + } +} diff --git a/reverse-words-in-a-string-iii/Cargo.toml b/reverse-words-in-a-string-iii/Cargo.toml new file mode 100644 index 0000000..b5d5baf --- /dev/null +++ b/reverse-words-in-a-string-iii/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "reverse-words-in-a-string-iii" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/reverse-words-in-a-string-iii/src/main.rs b/reverse-words-in-a-string-iii/src/main.rs new file mode 100644 index 0000000..473b428 --- /dev/null +++ b/reverse-words-in-a-string-iii/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn reverse_words(mut s: String) -> String { + unsafe {s.as_bytes_mut() }.split_mut(|&x| x == b' ').for_each(|x| x.reverse()); + s + } +} diff --git a/rotting-oranges-c/main.c b/rotting-oranges-c/main.c new file mode 100644 index 0000000..f1a4caf --- /dev/null +++ b/rotting-oranges-c/main.c @@ -0,0 +1,62 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MAX(a,b) (((a)>(b))?(a):(b)) + +int orangesRotting(int** grid, int gridSize, int* gridColSize) { + int *grid2 = malloc(sizeof(int) * gridSize * *gridColSize); + memcpy(grid2, *grid, sizeof(int) * gridSize * *gridColSize); + printf("%d %d\n", gridSize, *gridColSize); + + for (int minutes = 0;; minutes++) { + for (int x = 0; x < gridSize; x++) { + for (int y = 0; y < *gridColSize; y++) { + printf("%d ", (*grid)[x * gridSize + y]); + if ( (*grid)[x * gridSize + y] != 2 ) continue; + + for (int dx = MAX(x-1,0); dx < MIN(x+2, gridSize); dx++) + if ((*grid)[dx * gridSize + y] == 1) (grid2)[dx * gridSize + y] = 2; + for (int dy = MAX(y-1, 0); dy < MIN(y+2, *gridColSize); dy++) + if ((*grid)[x * gridSize + dy] == 1) (grid2)[x * gridSize + dy] = 2; + } + printf("\n"); + } + + int finished = 1; + int same = 1; + for (size_t i = 0; i < gridSize * *gridColSize; i++) { + if ((*grid)[i] == 1) finished = 0; + same &= (*grid)[i] == grid2[i]; + } + + if (finished) return minutes; + + if (same) return -1; + int *temp = *grid; + *grid = grid2; + grid2 = temp; + memcpy(grid2, *grid, sizeof(int) * gridSize * *gridColSize); + } + + return 0; +} + +int main() { + int *test1 = malloc(sizeof(int) * 3 * 3); + int test[] = {2,1,1,1,1,0,0,1,1}; + memcpy(test1, test, sizeof(int) * 3 * 3); + + int gridColSize = 3; + + int result = orangesRotting(&test1, 3, &gridColSize); + + printf("is %d expeceted %d\n", result, 4); + + assert(result == 4); +} + + + diff --git a/rotting-oranges/Cargo.toml b/rotting-oranges/Cargo.toml new file mode 100644 index 0000000..5202e07 --- /dev/null +++ b/rotting-oranges/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rotting-oranges" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/rotting-oranges/src/main.rs b/rotting-oranges/src/main.rs new file mode 100644 index 0000000..a975aa1 --- /dev/null +++ b/rotting-oranges/src/main.rs @@ -0,0 +1,81 @@ +fn main() { + let tests: Vec<Vec<Vec<i32>>> = vec![ + vec![ + vec![2,1,1], + vec![1,1,0], + vec![0,1,1] + ], + vec![ + vec![2,1,1], + vec![0,1,1], + vec![1,0,1] + ], + vec![ + vec![0,2] + ], + vec![ + vec![1,2] + ] + ]; + let outputs = [4,-1,0,1]; + for (n, test) in tests.iter().enumerate() { + let c: Vec<Vec<i32>> = test.to_vec(); + let result = oranges_rotting(c); + println!("test {} result {} should be {}", n, result, outputs[n]); + } +} + + +fn oranges_rotting(grid: Vec<Vec<i32>>) -> i32 { + let mut grid1 = grid.clone(); + let mut grid2 = grid1.clone(); + + let mut minutes: i32 = -1; + let mut some_fresh: bool = true; + let mut some_different: bool; + while some_fresh { + some_fresh = false; + some_different = false; + + // println!("Minute {}", minutes); + + for (x, row) in grid1.iter().enumerate() { + for (y, col) in row.iter().enumerate() { + some_fresh |= *col == 1; + if *col != 2 {continue;} + let r: [i32; 3] = [-1,0,1]; + for ix in r { + for iy in r { + if ix.abs() == iy.abs() {continue;} + let field: &mut i32 = &mut grid2[ + (x as i32 + ix).clamp(0,grid.len() as i32 -1) as usize + ][ + (y as i32 + iy).clamp(0,grid[0].len() as i32 -1) as usize + ]; + if *field == 1 { + some_different = true; + *field = 2; + } + } + } + } + // println!("{:?} {:?}", row, grid2[x]); + } + // for (x, row) in grid1.iter().enumerate() { + // for (y, col) in row.iter().enumerate() { + // some_different |= grid1[x][y] != grid2[x][y]; + // } + // } + + if !some_different && some_fresh { + // println!("impossible"); + return -1; + } + + grid1 = grid2; + grid2 = grid1.clone(); + minutes += 1; + } + return minutes; +} + diff --git a/rotting-oranges/src/main_2.rs b/rotting-oranges/src/main_2.rs new file mode 100644 index 0000000..6e806a7 --- /dev/null +++ b/rotting-oranges/src/main_2.rs @@ -0,0 +1,80 @@ +fn main() { + let tests: Vec<Vec<Vec<i32>>> = vec![ + vec![ + vec![2,1,1], + vec![1,1,0], + vec![0,1,1] + ], + vec![ + vec![2,1,1], + vec![0,1,1], + vec![1,0,1] + ], + vec![ + vec![0,2] + ], + vec![ + vec![1,2] + ] + ]; + let outputs = [4,-1,0,1]; + for (n, test) in tests.iter().enumerate() { + let c: Vec<Vec<i32>> = test.to_vec(); + let result = oranges_rotting(c); + println!("test {} result {} should be {}", n, result, outputs[n]); + } +} + + +fn oranges_rotting(grid: Vec<Vec<i32>>) -> i32 { + let mut grid1 = grid.clone(); + let mut grid2 = grid1.clone(); + + let mut minutes: i32 = -1; + let mut some_fresh: bool = true; + let mut some_different: bool; + while some_fresh { + some_fresh = false; + some_different = false; + + println!("Minute {}", minutes); + + for (x, row) in grid1.iter().enumerate() { + for (y, col) in row.iter().enumerate() { + some_fresh |= *col == 1; + if *col != 2 {continue;} + let r: [i32; 3] = [-1,0,1]; + for ix in r { + for iy in r { + if ix.abs() == iy.abs() {continue;} + let field: &mut i32 = &mut grid2[ + (x as i32 + ix).clamp(0,grid.len() as i32 -1) as usize + ][ + (y as i32 + iy).clamp(0,grid[0].len() as i32 -1) as usize + ]; + if *field == 1 { + *field = 2; + } + } + } + } + println!("{:?} {:?}", row, grid2[x]); + } + for (x, row) in grid1.iter().enumerate() { + for (y, col) in row.iter().enumerate() { + some_different |= grid1[x][y] != grid2[x][y]; + } + } + + if !some_different && some_fresh { + println!("impossible"); + return -1; + } + + grid1 = grid2; + grid2 = grid1.clone(); + minutes += 1; + } + return minutes; +} + diff --git a/search-insert-position/Cargo.toml b/search-insert-position/Cargo.toml new file mode 100644 index 0000000..a4b2727 --- /dev/null +++ b/search-insert-position/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "search-insert-position" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/search-insert-position/src/main.rs b/search-insert-position/src/main.rs new file mode 100644 index 0000000..50ad333 --- /dev/null +++ b/search-insert-position/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution {} +impl Solution { + pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 { + nums.partition_point(|&x| x < target) as i32 + // nums.binary_search(&target).unwrap_or_else(|x| x) as i32 + + } +} diff --git a/shortest-distance-to-a-character/Cargo.toml b/shortest-distance-to-a-character/Cargo.toml new file mode 100644 index 0000000..ce28cb0 --- /dev/null +++ b/shortest-distance-to-a-character/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "shortest-distance-to-a-character" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/shortest-distance-to-a-character/src/main.rs b/shortest-distance-to-a-character/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/shortest-distance-to-a-character/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/sort-array-by-parity/Cargo.toml b/sort-array-by-parity/Cargo.toml new file mode 100644 index 0000000..c67befb --- /dev/null +++ b/sort-array-by-parity/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "sort-array-by-parity" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/sort-array-by-parity/src/main.rs b/sort-array-by-parity/src/main.rs new file mode 100644 index 0000000..6deb88d --- /dev/null +++ b/sort-array-by-parity/src/main.rs @@ -0,0 +1,22 @@ +fn main() { + println!("Hello, world!"); + + let tests = [ + vec![3,1,2,4], + vec![0] + ]; + + for test in tests { + println!("{:?} {:?}", test, Solution::sort_array_by_parity(test.clone())); + } +} + +struct Solution; + +impl Solution { + pub fn sort_array_by_parity(nums: Vec<i32>) -> Vec<i32> { + let mut result = nums.clone(); + result.sort_by_key(|x| x % 2); + result + } +} diff --git a/sort-the-matrix-diagonally/Cargo.toml b/sort-the-matrix-diagonally/Cargo.toml new file mode 100644 index 0000000..8e05371 --- /dev/null +++ b/sort-the-matrix-diagonally/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "sort-the-matrix-diagonally" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/sort-the-matrix-diagonally/src/main.rs b/sort-the-matrix-diagonally/src/main.rs new file mode 100644 index 0000000..fa8d7e8 --- /dev/null +++ b/sort-the-matrix-diagonally/src/main.rs @@ -0,0 +1,26 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn diagonal_sort(mut mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> { + let mut a = HashMap::new(); + + for (i, row) in mat.iter().enumerate() { + for (ii, value) in row.iter().enumerate() { + a.entry(i-ii).and_modify(|x: &mut Vec<&i32>| {x.push(value)}).or_insert(vec![value]); + } + } + + for i in a.values_mut() { + i.sort(); + println!("{i:?}"); + } + + mat + } +} diff --git a/sum-root-to-leaf-numbers/Cargo.toml b/sum-root-to-leaf-numbers/Cargo.toml new file mode 100644 index 0000000..5d43227 --- /dev/null +++ b/sum-root-to-leaf-numbers/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "sum-root-to-leaf-numbers" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/sum-root-to-leaf-numbers/src/main.rs b/sum-root-to-leaf-numbers/src/main.rs new file mode 100644 index 0000000..57254ce --- /dev/null +++ b/sum-root-to-leaf-numbers/src/main.rs @@ -0,0 +1,40 @@ +// Definition for a binary tree node. +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option<Rc<RefCell<TreeNode>>>, + pub right: Option<Rc<RefCell<TreeNode>>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: i32) -> Self { + TreeNode { + val, + left: None, + right: None + } + } +} +use std::rc::Rc; +use std::cell::RefCell; + +struct Solution; +impl Solution { + pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { + Solution::sum_numbers_before(root, 0) + } + pub fn sum_numbers_before(root: Option<Rc<RefCell<TreeNode>>>, before: i32) -> i32 { + let Some(node) = root else {return 0;}; + let n = &node.borrow(); + let mut sum = 0; + if n.left.is_some() {sum += Solution::sum_numbers_before(n.left.clone(), before * 10 + n.val);} + if n.right.is_some() {sum += Solution::sum_numbers_before(n.right.clone(), before * 10 + n.val);} + sum + } +} + + +fn main() { + println!("Hello, world!"); +} diff --git a/two-sum/Cargo.toml b/two-sum/Cargo.toml new file mode 100644 index 0000000..540b825 --- /dev/null +++ b/two-sum/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "two-sum" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/two-sum/src/main.rs b/two-sum/src/main.rs new file mode 100644 index 0000000..8b18400 --- /dev/null +++ b/two-sum/src/main.rs @@ -0,0 +1,28 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + (vec![2,7,11,15], 9, vec![0,1]), + (vec![3,2,4], 6, vec![1,2]), + (vec![3,3], 6, vec![0,1]) + ]; + + for test in tests { + println!("{:?} at {} is {:?} should be {:?}", + test.0, + test.1, + two_sum(test.0.clone(), test.1), + test.2 + ); + } +} + +pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { + for i in 0..nums.len()-1 { + for ii in i+1..nums.len() { + if nums[i] + nums[ii] == target { + return vec![i as i32, ii as i32]; + } + } + } + return vec![0,0]; +} diff --git a/valid-palindrome/Cargo.toml b/valid-palindrome/Cargo.toml new file mode 100644 index 0000000..70e5242 --- /dev/null +++ b/valid-palindrome/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "valid-palindrome" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/valid-palindrome/src/main.rs b/valid-palindrome/src/main.rs new file mode 100644 index 0000000..e9ad1d4 --- /dev/null +++ b/valid-palindrome/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn is_palindrome(mut s: String) -> bool { + let str: Vec<u8> = unsafe { s.as_bytes_mut() }.iter_mut().filter(|x| x.is_ascii_alphanumeric()).map(|x| x.to_ascii_lowercase()).collect(); + str.iter().take(str.len() / 2).eq(str.iter().rev().take(str.len() / 2)) + } +} diff --git a/valid-parentheses/Cargo.toml b/valid-parentheses/Cargo.toml new file mode 100644 index 0000000..7b14741 --- /dev/null +++ b/valid-parentheses/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "valid-parentheses" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/valid-parentheses/src/main.rs b/valid-parentheses/src/main.rs new file mode 100644 index 0000000..5ee7e96 --- /dev/null +++ b/valid-parentheses/src/main.rs @@ -0,0 +1,39 @@ +fn main() { + let tests = vec![ + ("()", true), + ("()[]{}", true), + ("([", false) + ]; + + for test in tests { + println!("{} is {} should be {}", test.0, is_valid(test.0.to_string()).to_string(), test.1) + } +} + +fn is_valid(s: String) -> bool { + + let mut stack: Vec<char> = vec![]; + + for c in s.chars() { + match c { + '[' | '(' | '{' => stack.push(c), + ']' | ')' | '}' => { + match stack.pop() { + Some(head) => if lookup(head).unwrap() != c {return false;}, + None => return false + } + } + _ => {} + } + } + return stack.is_empty(); +} + +fn lookup(c: char) -> Option<char> { + match c { + '[' => Some(']'), + '(' => Some(')'), + '{' => Some('}'), + _ => None + } +} |