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 subsequenceand not a substring.
/**
思路:遍历的同时把每个字符索引记录在map中,然后计算当前字符和距离自己最远的不同的字符,
最终算出最长的符合要求的结果
*/
func lengthOfLongestSubstring(s string) int {
if(len(s) == 0) {
return 0
}
var charMap = make(map[byte]int)
var result = 0
var lastIndex = 0
for i := 0;i < len(s);i++ {
if index, ok := charMap[s[i]]; ok {
//记录有效字符的索引,也就是当前字符和距离自己最远的不同的字符索引
if (index + 1 > lastIndex) {
lastIndex = index + 1
}
}
charMap[s[i]] = i
//计算两个字符简的距离
var gap = (i - lastIndex + 1)
if (gap > result) {
result = gap
}
}
return result
}