LeetCode3-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.

分析:

  这题不难,但是需要注意一些细节,首先,必须要存储的信息有:(1)、当前最长无重复字符子串的起始位置。(2)、当前最长无重复字符子串的长度。(3)、由前两项信息可以截取字串,对下一个字符进行判断,若在字串中未找到该字符,则(1)中信息不变,(2)中信息要加1;若在字符串中找到该字符,返回该字符在字串中的位置,以(1)信息+重复位置+1作为新的起始位置,以(2)-重复位置作为新的(2)。

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        char cur;
        int max=1;
        int count=1;
        int index_begin,index_repeat;
        string curmax_string;
        if(s.length()==0)
        {
            return 0;
        }
        index_begin=0;
        for(int i=1;i<s.length();i++)
        {
            cur=s[i];
            curmax_string=s.substr(index_begin,count);
            if((index_repeat=curmax_string.find_last_of(cur))==string::npos)
            {
                count++;
                if(count>max)
                {
                    max=count;
                }
            }
            else
            {
                count = count - index_repeat;
                index_begin = index_begin+index_repeat+1;
            }
        }
        return max;
    }
};
原文地址:https://www.cnblogs.com/yanqi0124/p/4245005.html