Longest Substring Without Repeating Characters

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.

注意:最后面的子串最长,在循环外也要更新一次最大长度。

C++实现代码如下:

#include<iostream>
#include<string>
using namespace std;

class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        if(s.empty())
            return 0;
        if(s.length()==1)
            return 1;
        size_t i,j,k=0;
        //记录最大长度
        size_t maxLen=0;
        //记录最大长度开始的下标
        size_t index=0;
        for(i=1; i<s.length(); i++)
        {
            j=k;
            while(j<i)
            {
                if(s[j]==s[i])
                {
                    if(i-k>maxLen)
                    {
                        maxLen=i-k;
                        index=k;
                    }
                    k=j+1;
                    break;
                }
                else
                    j++;
            }
        }
        if(i-k>maxLen)
        {
            maxLen=i-k;
            index=k;
        }
        cout<<"index: "<<index<<endl;
        return maxLen;
    }
};

int main()
{
    Solution s;
    string ss="wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
    cout<<s.lengthOfLongestSubstring(ss)<<endl;
}

 

#include<iostream>
#include<string>
using namespace std;

class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        if(s.empty())
            return 0;
        int maxLen=1;
        int i,j,k;
        j=0;
        k=0;
        for(i=1; i<(int)s.size(); i++)
        {
            j=k;
            while(j<i)
            {
                if(s[i]!=s[j])
                    j++;
                else
                {
                    if(i-k>maxLen)
                        maxLen=i-k;
                    k=j+1;
                    break;
                }
            }
        }
        if(i-k>maxLen)
            maxLen=i-k;
        return maxLen;
    }
};

int main()
{
    Solution s;
    string ss="wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
    cout<<s.lengthOfLongestSubstring(ss)<<endl;
}

  

posted @ 2014-11-18 15:36  Jessica程序猿  阅读(171)  评论(0编辑  收藏  举报