Leetcode003. Longest Substring Without Repeating Characters

来源:互联网 发布:人工智能取代的职业 编辑:程序博客网 时间:2024/05/24 05:37

题目描述:

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.

题目大意:

求最长无重复字符子串

思路:

暴力算法:枚举子串再判是否有重复字符,时间复杂度O(n³),显然会TLE。

O(n)算法:记录每个字符上次出现的位置,具体见代码。

代码:

python:

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        pre = {} # 记录每个字符上次出现的位置        maxlen = 0 # 保存当前最长的长度        j = -1 # 当前字符串最远能向左延伸到哪里(若延伸太远则会遇到重复字符)        for i in range(len(s)):            c = s[i]            if c in pre: # 若字符c已出现过                j = max(j, pre[c]) # 则最远只能延伸到c上一次出现的位置之后,否则出现两个c            pre[c] = i # 更新c最后出现的位置            maxlen = max(maxlen, i - j) # 更新答案        return maxlen

c++:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int pre[256], last = -1, maxx = 0;        memset(pre, -1, sizeof(pre));        for (int i = 0; i < s.size(); i++)        {            last = max(last, pre[s[i]]);            maxx = max(maxx, i - last);            pre[s[i]] = i;        }        return maxx;    }};



原创粉丝点击