Leetcode每日一题:3.无重复字符的最长子串_数组
Leetcode每日一题:3.无重复字符的最长子串_编程题_02

双指针法

//双指针法
int lengthOfLongestSubstring(string s)
{
    int flag[130] = {0}; //标记数组
    int countMax = 0;    //记录长度
    int len = s.size();

    for (int i = 0, j = 0; j < len; j++) //i代表左指针,j代表右指针
    {
        flag[s[j]]++;          //标记该字符已出现过
        while (flag[s[j]] > 1) //说明该字符在前面已出现过,需移动左指针
        {
            flag[s[i++]]--; //保证左指针一定指向的没重复字符的子串的开头
        }
        countMax = j - i + 1 > countMax ? j - i + 1 : countMax;
    }
    return countMax;
}

暴力法
Leetcode每日一题:3.无重复字符的最长子串_编程题_03

int lengthOfLongestSubstring(string s)
{
    int flag[130] = {0}; //标记数组
    int cur = 1;
    int count = 0, countRes = 0; //记录长度
    int len = s.size();
    int i = 0;

    for (; i < len; i++)
    {
        if (flag[s[i]] == cur) //说明存在重复字符
        {
            cur++;
            if (count > countRes) //记录该子串
            {
                countRes = count;
            }
            i=i-count+1;
            count = 0;
        }
        count++;
        flag[s[i]] = cur; //记录该字符
    }
    if (i == len && count > countRes)
        countRes = count;
    return countRes;
}
}