3. Longest Substring Without Repeating Characters

来源:互联网 发布:网络社交的利与弊论点 编辑:程序博客网 时间:2024/06/06 01:40

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.

Subscribe to see which companies asked this question.

(1)先暴力求解:
使用2重外循环遍历所有的区间,用2重内循环检验子串是否符合“无重复字符”这一要求。其中外层循环i、j 遍历所有的下标,m、n是内层循环,检查区间[i,j]是否符合要求。空间复杂度是O(1),时间复杂度O(N^4)。

class Solution {public:    int lengthOfLongestSubstring(string s)     {        int maxlen=0;        int i, j;        int size = s.size();        for ( i= 0; i < size; ++i)        {            for (j = 1; j < size; ++j)            {                int flag = 0;                for (int m = i; m <=j; m++)                {                    for (int n = m + 1; n <=j; ++n)                    {                        if (s[n] == s[m])                        {                             flag = 1;                            break;                        }                    }                    if (flag == 1) break;                }                if (flag == 0 && j - i + 1>maxlen)                {                      maxlen = j - i + 1;                }            }        }        return maxlen;    }};

(2)精巧解法 看的很懵逼。

降低复杂度的方式:以空间换时间,这里我们可以用到一个数组来记录字符出现过没有。class Solution {public:    int lengthOfLongestSubstring(string s) {        int last[256]; //字符的ascII码0~256,记录字符最终出现的位置        memset(last, -1, sizeof(int) * 256);//初始化为-1 memset是计算机中C/C++语言函数。        int idx = -1;//用来当前字串开始的位置        int max = 0;        for (int i = 0; i < s.length(); ++i)        {            if (last[s[i]]!=idx)  //①如果这个字符出现过,则令idx等于上一次出现该字符的位置序号            {                idx = last[s[i]];                    }            if (i - idx > max) { //  ②记录最大的无重复字串                max = i - idx;            }            last[s[i]] = i;        }        return max;    }  };

(3)运用set ,把字符向里面添加 且删除重复元素,时间为O(n)
查找时间为O(lgn) 总时间为 O(n*lgn) ;

#include<string>#include<iostream>#include<set>#include<cmath>using namespace std;class Solution {public:    int lengthOfLongestSubstring(string s)    {        set<char> set1;        int size = s.size();        int ans=0, i=0, j = 0;        while (i < size&&j < size)        {            if (set1.find(s[j]) !=set1.end( )) //判断s[j]是否在set里面            {                set1.erase(s[i]);                i++;            }            else            {                set1.insert(s[j]);                j++;                if (j - i > ans)                    ans = j - i;            }        }        return ans;    }};        int main()        {            string s = "abcadba";            Solution s1;            cout<<s1.lengthOfLongestSubstring(s);            system("pause");        }

总的来说 解法二效率最高,但也最难理解。

阅读全文
0 0
原创粉丝点击