美文网首页
LeetCode之Longest Substring Witho

LeetCode之Longest Substring Witho

作者: 糕冷羊 | 来源:发表于2021-07-06 14:05 被阅读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))
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Longest Substring Witho

      本文链接:https://www.haomeiwen.com/subject/vddgultx.html