LeetCode 3 : Longest Substring Without Repeating Characters ---- 不重复的子串

来源:互联网 发布:hash算法详解 编辑:程序博客网 时间:2024/06/17 17:10

原题链接: https://leetcode.com/problems/longest-substring-without-repeating-characters/


一:原题内容

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 asubstring,"pwke" is asubsequence and not a substring.


二:AC代码

class Solution {public:    int lengthOfLongestSubstring(string s)     {        int flag[128]={0};        int ans=0;//the answer        int j=0;                for(int i=0;i<s.size();i++)        {            if(flag[s[i]]>0)            {                j=max(j,flag[s[i]]);            }                        flag[s[i]]=i+1;            ans=max(ans,i-j+1);        }                return ans;    }};


class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """                ret=0        left=0        d={}                for index,value in enumerate(s):            if value in d and d[value]>=left:                left=d[value]+1                            d[value]=index            ret=max(ret,index-left+1)        return ret




返回LeetCode 题解目录




1 0
原创粉丝点击