码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode No.3 Longest Substring Without Repeating Characters

时间:2015-01-11 22:58:44      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

这道题的意思是要找出给定字符串中不包含重复字符的最长子串。

算法不难,这里需要额外的空间记录每个字符是否已经出现过,以及一个头指针p和一个尾指针q。

循环每次向后移q,如果s[q]未出现,则标记为出现,否则在[p,q)范围内找到s[q]第一次出现的位置记为t,将p到t都标记为未出现,再将p更新为t+1,(别忘了标记当前正在处理的字符)直到处理完所有字符串为止。

实际上我在这里走了弯路。第一次通过的代码用时148ms,排在C++分布的后半部分了,代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        string t;
        bool hasAppeared[128];
        int max = 0, _pos;
    
    
        if (s.size() == 0 || s.size() == 1)
            return s.size();
    
        for (int i = 0; i < 128; i++)
            *(hasAppeared + i) = false;
    
        for (int i = 0; i < s.size(); i++) {
            if (!hasAppeared[s[i]]) {
                hasAppeared[s[i]] = true;
                t += s[i];
            }
            else {
                _pos = t.find(s[i]);
                max = max < t.size() ? t.size() : max;
                for (int j = 0; j <= _pos; j++)
                    hasAppeared[t[j]] = false;
                t = t.substr(_pos + 1);
                t += s[i];
                hasAppeared[s[i]] = true;
            }
        }
    
        max = max < t.size() ? t.size() : max;
    
        return max;
    }
};

因为对C++不是很熟悉,所以并不清楚有些API的实现。我猜测,应该是substr方法占用的时间较多。也许是拷贝了一份原字符串。当时还觉得这种写法看起来还比较elegant。

想了半天思路应该是没错的,于是换用了指针(下标),代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        bool hasAppeared[128];
        int i, max = 0, _pos, _st = 0;

        if (s.size() == 0 || s.size() == 1)
            return s.size();

        for (i = 0; i < 128; i++)
            *(hasAppeared + i) = false;

        for (i = 0; i < s.size(); i++) {
            if (!hasAppeared[s[i]]) {
                hasAppeared[s[i]] = true;
            }
            else {
                _pos = s.find(s[i], _st);
                max = max < i - _st ? i - _st : max;
                for (int j = _st; j <= _pos; j++)
                    hasAppeared[s[j]] = false;
                _st = _pos + 1;
                hasAppeared[s[i]] = true;
            }
        }

        max = max < i - _st ? i - _st : max;

        return max;
    }
};

技术分享

这样运行时间就缩短到了48ms,也基本算是最优了。每次我都很困惑,前面那些运行时间接近0的和快的超过数学最优解的到底是怎么回事。纠结无益,继续学习。

LeetCode No.3 Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/aovaegis/p/4217198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!