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.
简单的来说就是从给予的字符串中计算出没有重复字符串的最长子串的长度
最简单的 暴力破解
第二种解题思路是:从字符串中获取一个滑动子串,长度为0,然后遍历字符串,当当前定位的字符不存在与子串中时,则将其放入子串,子串长度加一,并记录最大长度,若已存在,则子串startIndex往前滑动一个位置子串长度减一,并移除第一个字符,然后重复步骤
方案1
func lengthOfLongestSubstring(s string) int {
max := 0
for i := 0; i < len(s); i++ {
for j := i+1; j <= len(s); j++ {
substr := s[i:j-1]
if !strings.Contains(substr, s[j-1:j]) {
if max < j-i {
max = j - i
}
} else {
break
}
}
}
return max
}
方案2
func lengthOfLongestSubstring(s string) int {
var max,start,end,length = 0,0,0,len(s)
for start < length && end < length{
if !strings.Contains(s[start:end],string(s[end])){
end = end +1
if end-start > max {
max = end-start
}
}else{
start = start+1
}
}
return max
}