forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0003_longest_substring.rs
50 lines (44 loc) · 1.2 KB
/
n0003_longest_substring.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* [3] Longest Substring Without Repeating Characters
*
* Given a string, find the length of the longest substring without repeating characters.
*
* Example:
*
* Input: "abcabcbb"
* Output: 3
* Explanation: The answer is "abc", with the length of 3.
*
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn length_of_longest_substring(s: String) -> i32 {
let seq: Vec<char> = s.chars().collect();
let len = seq.len();
let (mut start, mut end, mut max) = (0, 0, 0);
while end < len {
for idx in start..end {
if seq[end] == seq[idx] {
start = idx + 1;
break
}
}
let curr = end - start + 1;
if curr > max { max = curr }
end += 1
}
max as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3() {
assert_eq!(Solution::length_of_longest_substring("abcabcbb".to_string()), 3);
assert_eq!(Solution::length_of_longest_substring("bbbb".to_string()), 1);
assert_eq!(Solution::length_of_longest_substring("pwwkew".to_string()), 3);
}
}