LeetCode之Longest Substring Witho
2021-07-06 本文已影响0人
糕冷羊
问题:
方法:
通过Map记录字符和所在index,如果next字符在map中存在则开始重新统计,这样一次循环就可以获得最大的字符串长度。
class LongestSubstringWithoutRepeatingCharacters {
fun lengthOfLongestSubstring(s: String): Int {
if (s.length < 2) {
return s.length
}
var maxLength = 1
val map = mutableMapOf<Char, Int>()
map[s[0]] = 0
var index = 1
while (index <= s.lastIndex) {
val ch = s[index]
if (map.containsKey(ch)) {
map[ch]?.let {
index = it + 1
map.clear()
}
continue
}
map[ch] = index
if (map.size > maxLength) {
maxLength = map.size
}
index++
}
return maxLength
}
}
fun main() {
val input = "dvdf"
val longestSubstringWithoutRepeatingCharacters = LongestSubstringWithoutRepeatingCharacters()
print(longestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring(input))
}
有问题随时沟通