【滑动窗口】【leetcode】【中等】3.无重复字符的最长子串

题目:

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

例:

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是"abc",所以其长度为3

原题地址:

3. 无重复字符的最长子串

解题思路:

定义2个指针left和right分别向右移动,当right指向字符存在时,移动left;否则移动right。

int lengthOfLongestSubstring(char * s){
    int exist[256] = {0};
    char *left = s;
    char *right = s;
    int max = 0;
    while (*right != 0) {
        if (exist[*right] == 1) {
            exist[*left++] = 0; // 移除左侧字符,left右移
        } else {
            exist[*right++] = 1; // 记录该字符,right右移
            int t = right - left;
            if (t > max) max = t;
        }
    }
    return max;
}

猜你喜欢

转载自blog.csdn.net/hbuxiaoshe/article/details/113977769