Bootstrap

【LeetCode】无重复字符的最长子串Java题解

题目描述

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


示例 1:

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

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:

输入: s = ""
输出: 0


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路分析

  • 今天的算法每日一题,是求无重复字符的最长子串。直观的想法就是首先枚举子串,遇到重复的字符就停止,动态更新最长子串长度。代码实现如下:

通过代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int ans = 0;
        if (s == null || s.isEmpty()) {
            return ans;
        }
        
        Set occ = new HashSet<>();
        int n = s.length();
        int j = -1;
        for (int i = 0; i < n; i++) {
            if (i != 0) {
                occ.remove(s.charAt(i-1));
            }
            while (j + 1 < n && !occ.contains(s.charAt(j+1))) {
                occ.add(s.charAt(j+1));
                ++j;
            }
            ans = Math.max(ans, j - i + 1);
        }
        
        return ans;
    }
}

总结

  • 上述算法的时间复杂度是O(n * n), 空间复杂度是O(n)

  • 坚持算法每日一题,加油!