|
| 1 | +/** |
| 2 | + * [3] Longest Substring Without Repeating Characters |
| 3 | + * |
| 4 | + * Given a string s, find the length of the longest <span data-keyword="substring-nonempty">substring</span> without repeating characters. |
| 5 | + * |
| 6 | + * <strong class="example">Example 1: |
| 7 | + * |
| 8 | + * Input: s = "abcabcbb" |
| 9 | + * Output: 3 |
| 10 | + * Explanation: The answer is "abc", with the length of 3. |
| 11 | + * |
| 12 | + * <strong class="example">Example 2: |
| 13 | + * |
| 14 | + * Input: s = "bbbbb" |
| 15 | + * Output: 1 |
| 16 | + * Explanation: The answer is "b", with the length of 1. |
| 17 | + * |
| 18 | + * <strong class="example">Example 3: |
| 19 | + * |
| 20 | + * Input: s = "pwwkew" |
| 21 | + * Output: 3 |
| 22 | + * Explanation: The answer is "wke", with the length of 3. |
| 23 | + * Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. |
| 24 | + * |
| 25 | + * |
| 26 | + * Constraints: |
| 27 | + * |
| 28 | + * 0 <= s.length <= 5 * 10^4 |
| 29 | + * s consists of English letters, digits, symbols and spaces. |
| 30 | + * |
| 31 | + */ |
| 32 | +pub struct Solution {} |
| 33 | + |
| 34 | +// problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ |
| 35 | +// discuss: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query= |
| 36 | + |
| 37 | +// submission codes start here |
| 38 | + |
| 39 | +impl Solution { |
| 40 | + pub fn length_of_longest_substring(s: String) -> i32 { |
| 41 | + use std::{cmp::max, collections::HashMap}; |
| 42 | + |
| 43 | + let mut map = HashMap::<char, usize>::new(); |
| 44 | + let mut ans = 0; |
| 45 | + let mut left: usize = 0; |
| 46 | + let chars: Vec<char> = s.chars().collect(); |
| 47 | + for (index, ch) in chars.iter().enumerate() { |
| 48 | + match map.get(&ch) { |
| 49 | + Some(i) => { |
| 50 | + left = max(left, *i + 1); |
| 51 | + } |
| 52 | + None => {} |
| 53 | + } |
| 54 | + map.insert(*ch, index); |
| 55 | + ans = max(ans, (index - left + 1) as i32); |
| 56 | + } |
| 57 | + ans |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// submission codes end |
| 62 | + |
| 63 | +#[cfg(test)] |
| 64 | +mod tests { |
| 65 | + use super::*; |
| 66 | + |
| 67 | + #[test] |
| 68 | + fn test_3() { |
| 69 | + assert_eq!( |
| 70 | + Solution::length_of_longest_substring(String::from("abcabcbb")), |
| 71 | + 3 |
| 72 | + ); |
| 73 | + assert_eq!( |
| 74 | + Solution::length_of_longest_substring(String::from("bbbbb")), |
| 75 | + 1 |
| 76 | + ); |
| 77 | + assert_eq!( |
| 78 | + Solution::length_of_longest_substring(String::from("pwwkew")), |
| 79 | + 3 |
| 80 | + ); |
| 81 | + assert_eq!( |
| 82 | + Solution::length_of_longest_substring(String::from("abba")), |
| 83 | + 2 |
| 84 | + ); |
| 85 | + } |
| 86 | +} |
0 commit comments