Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝客知名论坛 编辑:程序博客网 时间:2024/06/03 16:58

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.

只需要一次遍历

class Solution {public:    int lengthOfLongestSubstring(string s) {        int a[256];        memset(a,-1,sizeof(a));        int ans=0;        int start=-1;        for(int i=0;i<s.size();i++)        {            char c=s[i];            if(a[c]>start)            start=a[c];                        ans=max(ans,i-start);            a[c]=i;        }        return ans;    }};

还有一个复杂度高的算法

class Solution {public:    int lengthOfLongestSubstring(string s) {        int len=0;        int pre=0;        for(int i=0;i<s.size();i++)        {            unordered_map<char,int>hash;                        len=0;            char ch;            for(int j=i;j<s.size();j++)            {                ch=s[j];                                if(hash.find(ch)!=hash.end())                 break;                 hash[ch]=1;                 len++;                            }                        if(len>pre)pre=len;            hash.clear();                            }        return pre;                    }};


    

原创粉丝点击