题目说明:
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.
https://leetcode.com/problems/longest-substring-without-repeating-characters/
解题思路一:
给定字符串上某个位置用 i 表示,令 j 从 i 开始,往下遍历这个字符串的每个字符直到字符串结束。使用一个hash结构保存遍历过程中,是否出现过某个字符,一旦发现位置 j 上的字符已经出现过,则跳出循环;此时从位置 i 开始,不重复的子串长度为 j-i。如果这个长度大于 已知的最大不重复子串长度maxlen,则将 maxlen 更新为 j-i。
显然,此解法的时间复杂度为 O(n^2)。
Go代码如下:
func lengthOfLongestSubstring(s string) int {
str := []rune(s)
maxlen := 0
for i := 0; i < len(str); i++ {
var strmap = make(map[rune] bool)
j := i
for ; j < len(s); j++ {
if v, ok := strmap[str[j]]; ok {
_ = v
break
} else {
strmap[str[j]] = true
}
}
if j-i > maxlen {
maxlen = j-i
}
}
return maxlen
}
语言技巧:
因为如果字符串出现中文等多字节字符,则不能简单通过字符串下标取得一个字符,所以把字符串转为字符数组切片类型,这样可以通过下标访问每个字符。
待补充。。。