LeetCode-0003 characters without repeating the longest substring

topic

Given a string, you find out which does not contain the longest sub-string [] repeated characters in length.

Example 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

Example 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

Example 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。

请注意,你的答案必须是【子串】的长度,"pwke" 是一个子序列,不是子串。

Ideas analysis

Time efficiency is poor brute force, is not considered.

The provided to the character string length n, the first line with the requirements of the subject character substring in the original string all the possibilities: 0,1, ......, n-1. Sequentially traversing substring [k, *), k = 0,1, ......, n-1 can.

answer

func lengthOfLongestSubstring(s string) int {
    chars := []rune(s)
    n := len(chars)
    if n == 0 {
        return 0
    }

    res := 1

    for i := 0; i < n; i++ {
        // 检查以 i 开头的字串是否唯一

        m := map[rune]int{}
        m[chars[i]] = i

        curr := 1 // 本次循环找到的最大长度

        for j := i + 1; j < n; j++ {
            if _, in := m[chars[j]]; in {
                break
            } else {
                m[chars[j]] = j
                curr++
            }
        }

        if curr > res {
            res = curr
        }
    }

    return res
}

Guess you like

Origin www.cnblogs.com/jthmath/p/12345429.html
Recommended