Long substring without repeating

Time:2021-5-31

Title:

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Title Translation:

Find the longest length of a string that does not contain duplicate letters

Topic idea:

Create a dictionary and a start flag. The dictionary is used to store the position where the letter appears. When we traverse the string, if the position of the letter stored in the dictionary is less than the start mark, we think that there is no duplicate subtitle from the start; Otherwise, it is considered that there is repetition. At this time, move the start flag to the current position, and then continue to traverse from the start position. The distance between the traversal position and the starting mark is the length of the string without repeated characters. In the traversal process, we can find the maximum value and pay attention to the boundary conditions.

code:

use std::cmp;

fn length_of_longest_substring(s: String) -> i32 {
    let mut ret: i32 = 0;
    let mut start: i32 = -1;

    let mut dic = vec![-1; 128];

    let b = s.as_bytes();
    for i in (0..s.len()) {
        // if repeat just move the start
        if (dic[b[i as usize] as usize] > start) {
            start = dic[b[i as usize] as usize]
        }

        ret = std::cmp::max(ret, i as i32 - start);
        dic[b[i as usize] as usize] = i as i32;
    }

    return ret as i32;
}

#[test]
fn test_length_of_longest_substring() {
    let case1 = String::from("abcabcbb");
    let case2 = String::from("bbbbb");
    let case3 = String::from("pwwkew");

    assert_eq!(length_of_longest_substring(case1), 3);
    assert_eq!(length_of_longest_substring(case2), 1);
    assert_eq!(length_of_longest_substring(case3), 3);
}