LeetCode 3
### Description:
Given a string, find the length of the longest substring without repeating characters.
-
题意:
输入一个字符串, 输出最长不重复子串的长度 -
思路:
比较一般的思路是, 只要是有关于重复的应该想到字典, 两层遍历即可。
这里提供一种比较好的思路, 维护两个变量 last 和 index,last为此时不重复子串的开头,index为遍历字符串的下标,一旦index的遍历过程中遇到重复值, 则更新last的位置, 保证这两个位置之间的字符是不重复的, 这里用一个数组保存字符出现的上一个位置来代替字典的作用,画了个图助于理解, 具体看代码
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
---|---|---|---|---|---|---|---|---|
要查找串 | a | b | c | d | c | a | b | c |
初始位置 | last, index | |||||||
第一次找到重复 | last | index | ||||||
更新last位置 | last | index |
...
Example:
-
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.
代码
Golang
func lengthOfLongestSubstring(s string) int {
// last 为目前子串的开始, max为最大长度, count为计数
last, max, count := 1, 0, 0
// 128是因为128个ASCII字符, 这个数组保存某个字符上一个出现位置
m := [128]int{}
for index, value := range s {
if m[value] < last {
count++
} else {
last = m[value]
if count > max {
max = count
}
count = index - last + 1
}
m[value] = index + 1
}
if count > max {
max = count
}
return max
}