Longest Substring Without Repeating Characters

Description

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

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

在给定字符串中找出无重复字符的最长子串。

Solution

 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
func lengthOfLongestSubstring(s string) int {
    l := len(s)
    maxLen := 0

    for p1 := 0; p1 < l; p1++ {
        m := map[uint8]bool{}

        for p2 := p1; p2 < l; p2++{
            c := s[p2]

            _, ok := m[c]
            if ok {
                break
            } else {
                m[c] = true
            }
        }

        if len(m) > maxLen {
            maxLen = len(m)
        }
    }

    return maxLen
}

Similar Problem

5. Longest Palindromic Substring