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 a substring, “pwke” is a subsequence and not a substring.

1.个人分析
直观的思路是从头到尾遍历一次字符串,利用两个指针,第一个指向起始处,第二个从第一个的下一个位置开始遍历,直到遇到与第一个指针相同的字符或字符串的结尾。另一种思路是借助哈希表来查找最长无重复的子串。

2.个人解法

int lengthOfLongestSubstring(string s)
{
    string longSub;     //保存最长子串
    int strLen = s.length();
    for (int i=0; i<strLen; ++i){
        string tmp;
        tmp.push_back(s[i]);
        for (int j=i+1; j<strLen; ++j){
            //查找并保存当前无重复子串
            if(tmp.find(s[j]) != string::npos)
                break;              
            tmp.push_back(s[j]);
        }
        //比较无重复子串长度
        if(tmp.length() > longSub.length()){
            longSub.assign(tmp);
        }
    }

    return longSub.length();
}

该解法的时间复杂度为O(n^2)

3.参考解法

int lengthOfLongestSubstring(string s)
{
    vector<int> dict(256, -1);
    int maxLen = 0, start = -1;
    for (int i = 0; i != s.length(); i++) {
        if (dict[s[i]] > start)
            start = dict[s[i]];
        dict[s[i]] = i;
        maxLen = max(maxLen, i - start);
    }
    return maxLen;
}

该解法的时间复杂度为O(n),空间复杂度为O(1),运行结果显示时间效率非常的高。

4.总结
参考解法其实也是哈希表的一种形式,因为所有的测试字符都是ANSI II字符集,所以可以设定一个固定长度的字典。如果字符集是其他形式的话,则哈希表则是不定长的。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值