LeetCodeHot100(8/100)Java

张开发
2026/5/22 17:51:10 15 分钟阅读
LeetCodeHot100(8/100)Java
法一滑动窗口右指针遍历移动遇到重复的字符while移动左指针class Solution {public int lengthOfLongestSubstring(String s) {int n s.length();SetCharacter set new HashSet();int max 0;int left 0;for (int right 0; right n; right) {char c s.charAt(right);// 重复了就移动左指针while (set.contains(c)) {set.remove(s.charAt(left));left;}set.add(c);max Math.max(max, right - left 1);}return max;}}法二究极暴力遍历法(不推荐没有思路所以暴力解了)class Solution {public int lengthOfLongestSubstring(String s) {int n s.length();//先判空if (n 0) {return n;}//默认最长字串长度int max 1;//计数器int count 0;//列表主要用于判重ListCharacter list new ArrayList();//起始指针复杂度应该至少了int start 0;for (int i 0; i n; i) {if (list.contains(s.charAt(i))) {//判重更新长度和起点指针清空列表start;i start;list.clear();max max count ? max : count;count 0;}list.add(s.charAt(i));count;}//不重复别忘了更新max max count ? max : count;return max;}}

更多文章