牛客网刷题-找到字符串的最长无重复字符子串

问题描述

给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。

示例

示例1

输入
[2,3,4,5]

输出
4

解决思路

思路

  1. 双下标法:start为元素不重复的起始节点,end为结束节点,不断更新max值

代码实现

// 思路1:线性表
public class Solution {
    
      
    public int maxLength (int[] arr) {
    
    
        HashMap<Integer,Integer> map = new HashMap<>();
        int max = 1;
        for(int start = 0, end = 0; end<arr.length ; end++){
    
    
            if(map.containsKey(arr[end])){
    
    
                //重复了
                start = Math.max(start, map.get(arr[end])+1);
                //注意:这里一定要取最大的start,不然就错误了
                //为什么? 因为重复数字的索引很可能比start小
            }
            max = Math.max(max , end-start+1);
            map.put(arr[end],end);
        }
        return max;
    }
}

时间复杂度分析:
O(N):遍历数组

空间复杂度分析:
O(N):假设数组的元素都不重复,则map所占的空间为N

小伙伴如果想测试的话,可以直接到牛客网这个链接做测试

找到字符串的最长无重复字符子串-牛客网

猜你喜欢

转载自blog.csdn.net/qq_35398517/article/details/114397988