3. Longest Substring Without Repeating Characters

来源:互联网 发布:科勒橱柜 知乎 编辑:程序博客网 时间:2024/06/05 06:49

3. Longest Substring Without Repeating Characters
Difficulty: Medium

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.

给定一个字符串,找到不含相同字母的最长子字符串,返回该子字符串的长度。
如:给定”abcabcbb”—-“abc”—-len=3
给定”bbbbb”—-“b”—-len=1
给定”pwwkew”—-“wke”—-len=3

思路:用一个变量start标记当前子串的头,一个标记子串尾。不断往后扫描,当有字符前面出现过了,记录当前子串的长度和maxlen的比较结果。然后更新start标记。

方法一:时间复杂度=O(n^2),空间复杂度=O(1)

class Solution {public:    int lengthOfLongestSubstring(string s);};int Solution::lengthOfLongestSubstring(string s){    if (s == "")    {        return 0;    }    int len = 1;    int maxlen = 1;    int start = 0;    for (int i = 1; i<s.size(); i++)    {        int j;        for (j = start; j<i; j++)        {            if (s[j] == s[i]) //当前字符重复了,更新start和len            {                start = j + 1;                len = i - start + 1;                break;            }        }        if (j == i) //当前字符没有重复        {            len++;            if (len>maxlen)            {                maxlen = len;            }        }    }    return maxlen;}

方法二:时间复杂度=O(n)+O(n)=O(n),空间复杂度=O(256)

class Solution {public:    int lengthOfLongestSubstring(string s);};int Solution::lengthOfLongestSubstring(string s){    bool *type=new bool[256];    memset(type,false,256);    int len=0;    int maxlen=0;    int start=0;    for(int i=0;i<s.size();i++)    {        if(type[s[i]]==false)  //当前字符没有重复        {            len++;            type[s[i]]=true;        }        else                   //当前字符与前面的字符重复        {            while(s[start]!=s[i])  //重新记录子字符串的start和长度            {                type[s[start]]=false;                start++;            }            start++;            len=i-start+1;        }        if(len>maxlen)        {            maxlen=len;        }    }    delete [] type;    return maxlen;}

可以用hash表来代替type[256],查找当前字符是否已经出现过,在字符串较短时可以降低空间复杂度。

0 0
原创粉丝点击