1. 题目

1.1 英文

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

Examples:

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.

1.2 中文

给予一个字符串,找出它的最长不含有重复字符的子串,返回长度。

例如
字符串是"abcabcbb",答案就是"abc",长度是3。
字符串是"bbbbb",答案就是"b",长度是1。
字符串是"pwwkew",答案就是"wke",长度是3;注意必须是原字符串的子串,比如"pwke"符合规则但并不是子串。

2. 解答

以下是解法分析,使用Go语言来实现:

按顺序遍历字符串的字符,定义一个 lastOccurred 记录字母上次出现的位置,定义一个 start 记录符合规则的字符串的起始位置。

如果字母上次出现超过了 start ,说明重复出现了,不符合,start重新赋值

func lengthOfLongestSubstring(s string) int {
    lastOccurred := make(map[rune]int)
    start := 0
    maxLength := 0

    for i, ch := range []rune(s) {
        if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
            start = lastOccurred[ch] + 1
        }

        if i - start + 1 > maxLength {
            maxLength = i - start + 1
        }

        lastOccurred[ch] = i
    }

    return maxLength
}