跳至主要內容

滑动窗口问题

小于 1 分钟

滑动窗口问题

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

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

我的实现

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null){
            return 0;
        }
        if (s.length() == 1){
            return 1;
        }
        int maxLength = 0;
        Map<Character, Integer> temp = new HashMap<>();
        int startIndex = 0;
        for (int i=0;i<s.length();){
            char c = s.charAt(i);
            if (temp.containsKey(c)){
                maxLength = Math.max(maxLength, i - startIndex);
                temp.clear();
                startIndex++;
                i = startIndex;
            }else {
                i++;
                temp.put(c, i);
            }
        }
        maxLength = Math.max(maxLength, temp.size());
        return maxLength;
    }
}

别人的实现

 public int lengthOfLongestSubstring(String s) {
     // 记录字符上一次出现的位置
     int[] last = new int[128];
     for(int i = 0; i < 128; i++) {
         last[i] = -1;
     }
     int n = s.length();

     int res = 0;
     int start = 0; // 窗口开始位置
     for(int i = 0; i < n; i++) {
         int index = s.charAt(i);
         start = Math.max(start, last[index] + 1);
         res   = Math.max(res, i - start + 1);
         last[index] = i;
     }

     return res;
 }
上次编辑于:
贡献者: 诗人都藏在水底