leetcode3. Longest Substring Without Repeating Characters

leetcode3. Longest Substring Without Repeating Characters

题意:

给定一个字符串,找到最长子串的长度,且该字串不含不重复字符。

思路:

用map存储,key为字符,value为index;
O(n),遍历字符串,动态规划,一开始确定start的index,然后遍历,每次遍历的字符记作char,只要char对应map中value小于start,长度就在一直伸长,一旦大于或等于start,说明前一个该字符在start之后出现过一次,所以吧start点移动至前一个map[char]的index的下一位,更新map,然后继续遍历。

ac代码:

C++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res=0;
        int map[256];
        memset(map,-1,sizeof(map));
        int start = 0,temp = 0;
        
        for(int i=0;i<s.length();i++)
        {
            if(start <= map[s[i]])
            {                
                start = map[s[i]] + 1;
                temp = i - start + 1;                
            }
            else
            {
                if(++temp > res) res = temp;
            }
            map[s[i]] = i;
        }
        return res;
    }
};

python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        char_map = {}
        start = temp = res = 0
        for i in range(len(s)):
            if s[i] in char_map and start <= char_map[s[i]]:
                start = char_map[s[i]] + 1
                temp = i - start +1
            else:
                temp += 1
                res = max(res, temp)
            char_map[s[i]] = i
        return res
原文地址:https://www.cnblogs.com/weedboy/p/7143410.html