LeetCode之无重复字符的最长子串

1.题目链接

3. 无重复字符的最长子串 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/

2.题目解析

题目主要思路其实是滑动窗口,使用两个指针维护一个动态区间,使得这个区间内的子串没有重复字符。

3.代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {

        int f[128];

        memset(f,0,sizeof f);

        int maxi=0,sum=0;

        for(int i=0,j=0;j<s.size();)
        {
            if(!f[s[j]])
            {
                sum++;
                f[s[j]]++;
                j++;
                maxi=max(maxi,sum);
            }
            else
            {
                f[s[i]]--;
                i++;
                sum--;
            }
        }
        return maxi;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_74732859/article/details/140304592