3. Longest Substring Without Repeating Characters Medium
1/**
2 * [3] Longest Substring Without Repeating Characters
3 *
4 * Given a string s, find the length of the longest substring without repeating characters.
5 *
6 * Example 1:
7 *
8 * Input: s = "abcabcbb"
9 * Output: 3
10 * Explanation: The answer is "abc", with the length of 3.
11 *
12 * Example 2:
13 *
14 * Input: s = "bbbbb"
15 * Output: 1
16 * Explanation: The answer is "b", with the length of 1.
17 *
18 * 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 * Example 4:
26 *
27 * Input: s = ""
28 * Output: 0
29 *
30 *
31 * Constraints:
32 *
33 * 0 <= s.length <= 5 * 10^4
34 * s consists of English letters, digits, symbols and spaces.
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/
40// discuss: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn length_of_longest_substring(s: String) -> i32 {
46 let seq: Vec<char> = s.chars().collect();
47 let len = seq.len();
48 let (mut start, mut end, mut max) = (0, 0, 0);
49
50 while end < len {
51 for idx in start..end {
52 if seq[end] == seq[idx] {
53 start = idx + 1;
54 break;
55 }
56 }
57 let curr = end - start + 1;
58 if curr > max {
59 max = curr
60 }
61 end += 1
62 }
63 max as i32
64 }
65}
66
67// submission codes end
68
69#[cfg(test)]
70mod tests {
71 // use super::*;
72
73 #[test]
74 fn test_3() {
75 }
76}
77
Back
© 2025 bowen.ge All Rights Reserved.