Longest Substring Without Repeating Characters

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.

package leetcode

import "fmt"

func lengthOfLongestSubstring(s string) int {
	l := len(s)
	i := 0
	j := 0
	ans := 0
	set := make(map[byte]bool)
	for i < l && j < l {
		if !set[s[j]] {
			set[s[j]] = true
			j += 1
			if j-i > ans {
				ans = j - i
			}
		} else {
			delete(set, s[i])
			i += 1
		}
	}
	return ans
}

func TestLengthOfLongestSubstring() {
	fmt.Println(lengthOfLongestSubstring("abcabcdefabcdedght"))
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注