From d0dddf4ca6247db8e8b26ba7c0763f27dd8e5b06 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 15 Dec 2023 11:31:07 +0800 Subject: [PATCH] 20231215 Finished --- src/solution/mod.rs | 1 + ..._substring_without_repeating_characters.rs | 74 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/solution/s0003_longest_substring_without_repeating_characters.rs diff --git a/src/solution/mod.rs b/src/solution/mod.rs index f37f7e4..5e2b42e 100644 --- a/src/solution/mod.rs +++ b/src/solution/mod.rs @@ -3,3 +3,4 @@ mod s0009_palindrome_number; mod s0020_valid_parentheses; mod s2697_lexicographically_smallest_palindrome; mod s0002_add_two_numbers; +mod s0003_longest_substring_without_repeating_characters; diff --git a/src/solution/s0003_longest_substring_without_repeating_characters.rs b/src/solution/s0003_longest_substring_without_repeating_characters.rs new file mode 100644 index 0000000..41ebc6d --- /dev/null +++ b/src/solution/s0003_longest_substring_without_repeating_characters.rs @@ -0,0 +1,74 @@ +/** + * [3] Longest Substring Without Repeating Characters + * + * Given a string s, find the length of the longest substring without repeating characters. + * + * Example 1: + * + * Input: s = "abcabcbb" + * Output: 3 + * Explanation: The answer is "abc", with the length of 3. + * + * Example 2: + * + * Input: s = "bbbbb" + * Output: 1 + * Explanation: The answer is "b", with the length of 1. + * + * Example 3: + * + * Input: s = "pwwkew" + * Output: 3 + * Explanation: The answer is "wke", with the length of 3. + * Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + * + * + * Constraints: + * + * 0 <= s.length <= 5 * 10^4 + * s consists of English letters, digits, symbols and spaces. + * + */ +pub struct Solution {} + +// problem: https://leetcode.cn/problems/longest-substring-without-repeating-characters/ +// discuss: https://leetcode.cn/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +use std::cmp::max; +use std::collections::HashSet; +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let chars: Vec = s.chars().collect(); + let mut window = HashSet::new(); + let mut left = 0; + let mut result = 0; + + for i in 0..chars.len() { + while window.contains(&chars[i]) { + window.remove(&chars[left]); + left += 1; + } + + window.insert(chars[i]); + result = max(result, window.len()); + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3() { + assert_eq!(3, Solution::length_of_longest_substring(String::from("abcabcbb"))); + assert_eq!(1, Solution::length_of_longest_substring(String::from("bbbbb"))); + assert_eq!(3, Solution::length_of_longest_substring(String::from("pwwkew"))); + } +}