3. 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.
func lengthOfLongestSubstring(s string) int {
arr := make(map[rune]int)
start := 0
maxlen := 0
for i, v := range []rune(s) {
if pre, ok := arr[v]; ok && pre >= start {
start = pre + 1
}
if i-start+1 > maxlen {
maxlen = i - start + 1
}
arr[v] = i
}
return maxlen
}
近期评论