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

Longest Substring Without Repeating Characters

时间:2014-11-17 22:29:25      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

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.

描述:即最长不重复子序列,具体思路参考我的博文。

O(n)解法。

class Solution {
private:
    struct myarray{
        bool dp;
        int loc;
    };
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
        struct myarray dps[1000];
        for (int i=0; i<1000; ++i) {
            dps[i].dp=false;
            dps[i].loc=-1;
        }
        int reslen=0;
        int nextStart=0;
        int i;
        for(i=0;i<s.size();++i)
        {
            if(dps[s[i]].dp==false)
            {
                dps[s[i]].dp=true;
                dps[s[i]].loc=i;
            }
            else
            {
                if(i-nextStart>reslen)
                    reslen=i-nextStart;
                nextStart=dps[s[i]].loc+1;
                i=nextStart-1;
                for (int i=0; i<1000; ++i)
                {
                    dps[i].dp=false;
                    dps[i].loc=-1;
                }
            }
        }
        if(i==s.size())
            if(s.size()-nextStart>reslen)
                reslen=s.size()-nextStart;
        return reslen;
    }
};

 

Longest Substring Without Repeating Characters

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/fightformylife/p/4104390.html

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