3. 无重复字符的最长子串 Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
方法一:
还是暴力法。双层for循环,第一层第一个a元素开始循环时,将a以及之后元素依次放入set。如果set中有重复元素,退出。
public int lengthOfLongestSubstring(String s) { int max=0; for(int i = 0; i < s.length(); i++){ Set<Character> set = new HashSet<>(); for(int j = i; j< s.length(); j++){ if (set.contains(s.charAt(j))){ if (max < j - i){ max = j - i; } break; }else{ set.add(s.charAt(j)); } } } return max; }
时间复杂度 O(n^2)
方法二:
滑动窗口法。就是如果存在重复的元素,则我们可以把左侧窗口右移一到j-i位,直到没有重复的。
public int lengthOfLongestSubstring_set(String s) { int n = s.length(); Set<Character> set = new HashSet<>(); int ans = 0, i = 0, j = 0; while (i < n && j < n) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans; }
时间复杂度O(2n)=O(n)
方法三:
滑动窗口法。区别在于左侧不是移动一位,而是用map记录下重复的位置,直接移动到窗口左侧和重复位置的最大值。
public int lengthOfLongestSubstring_map(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; }
方法四:
滑动窗口法。区别在,认为不重复的字符有128(或256) 个。 用128维数组记录字符出现的位置。
public int lengthOfLongestSubstring_char(String s) { int n = s.length(), ans = 0; int[] index = new int[128]; // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { Character c = s.charAt(j); i = Math.max(index[c], i); ans = Math.max(ans, j - i + 1); index[c] = j + 1; } return ans; }
方法五:
滑动窗口法。类似与方法四。
public int lengthOfLongestSubstring_2(String s) { int max = 0; char allChar [] = new char[256]; for(int l = 0, r = 0; r < s.length();){ int c = s.charAt(r); if(allChar[c]==0){ allChar[c]++; r++; max = Math.max(max,r-l); }else{ allChar[s.charAt(l++)]--; } } return max; }
参考链接:
https://leetcode.com/problems/longest-substring-without-repeating-characters/
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具