码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 3

时间:2018-03-12 22:54:30      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:int   计数   理解   example   字符串   div   enc   with   desc   


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:


  1. Given "abcabcbb", the answer is "abc", which the length is 3.

  2. Given "bbbbb", the answer is "b", with the length of 1.

  3. 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
}

LeetCode 3

标签:int   计数   理解   example   字符串   div   enc   with   desc   

原文地址:https://www.cnblogs.com/shengwudiyi/p/8552240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!