|
| 1 | +// 1208. Get Equal Substrings Within Budget |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/get-equal-substrings-within-budget/ |
| 5 | +// |
| 6 | +// Tags: String - Binary Search - Sliding Window - Prefix Sum |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Get a vector of the cost of converting each character, after that use a sliding window, |
| 11 | + /// since we are looking for the largest window, we can only allow the window to grow, not |
| 12 | + /// shrink, and only update the max length when the window does grow. |
| 13 | + /// |
| 14 | + /// Time complexity: O(n) - We visit each element and do constant time work, both constructing |
| 15 | + /// the vector of sums and during the sliding window. |
| 16 | + /// Space complexity: O(n) - The sums vector. Since in Rust we cannot access string characters |
| 17 | + /// by index, I am not too sure how we could do it in O(1) |
| 18 | + /// |
| 19 | + /// Runtime 1 ms Beats 100% |
| 20 | + /// Memory 2.64 MB Beats 44% |
| 21 | + pub fn equal_substring(s: String, t: String, max_cost: i32) -> i32 { |
| 22 | + let mut l = 0; |
| 23 | + let sums = s |
| 24 | + .bytes() |
| 25 | + .zip(t.bytes()) |
| 26 | + .map(|(x, y)| (x as i32 - y as i32).abs()) |
| 27 | + .collect::<Vec<_>>(); |
| 28 | + let mut cost = 0; |
| 29 | + let mut max_length = 0; |
| 30 | + for r in 0..sums.len() { |
| 31 | + cost += sums[r]; |
| 32 | + if cost > max_cost { |
| 33 | + cost -= sums[l]; |
| 34 | + l += 1; |
| 35 | + } else { |
| 36 | + max_length = r - l + 1; |
| 37 | + } |
| 38 | + } |
| 39 | + max_length as i32 |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// Tests. |
| 44 | +fn main() { |
| 45 | + let tests = [ |
| 46 | + ("abcd", "bcdf", 3, 3), |
| 47 | + ("abcd", "cdef", 3, 1), |
| 48 | + ("abcd", "acde", 0, 1), |
| 49 | + ]; |
| 50 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 51 | + let mut success = 0; |
| 52 | + for (i, t) in tests.iter().enumerate() { |
| 53 | + let res = Solution::equal_substring(t.0.to_string(), t.1.to_string(), t.2); |
| 54 | + if res == t.3 { |
| 55 | + success += 1; |
| 56 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 57 | + } else { |
| 58 | + println!( |
| 59 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 60 | + i, t.3, res |
| 61 | + ); |
| 62 | + } |
| 63 | + } |
| 64 | + println!(); |
| 65 | + if success == tests.len() { |
| 66 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 67 | + } else if success == 0 { |
| 68 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 69 | + } else { |
| 70 | + println!( |
| 71 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 72 | + tests.len() - success |
| 73 | + ) |
| 74 | + } |
| 75 | +} |
0 commit comments