最长不重复子串 C++

class Solution1
{
public:
    /*********************************************
    *函数功能:最长不重复子串
    *参数说明
    *    输入:
    *    输出:
    *时间复杂度:O( n) 空间复杂度 O( )
    *日期:      2018-07-24-00.15
    ***********************************************/
    string no_redup(string str)
    {
        if(str.size()<1) return "";
        int mp[256]={0};
        int begins=0;
        string word="";
        string longest_word="";
        for(int i=0;i<str.size();i++)
        {
            mp[str[i]]++;
            if(mp[str[i]]==1)
            {
                word+=str[i];
                if(word.size()>longest_word.size())
                {
                    longest_word=word;
                }
            }else
            {
                while(i>begins && mp[str[i]]>1)
                {
                    mp[str[begins]]--;
                    begins++;
                }
                word="";
                for(int k=begins;k<=i;k++)
                {
                    word+=str[k];
                }
            }
        }
        return longest_word;
    }
};

int main()
{
    Solution1 s;
    string result;
    string str="abcdefgegcsgcasse";
    result=s.no_redup(str);
    cout<<result<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csu_guo_liang/article/details/81177271