LeetCode: 3 无重复字符的最长子串 (Java)

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

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 

最初始的解法方法就是遍历暴力每个元素,然后以那个元素为起始点,然后进行判断是否出现了重复元素,这样时间的复杂度就是O(n2),这样的时间复杂度有点高,基本上已经预定了时间超出限制。所以我们要用别的解法方法。 
那么比较好的解决方法就是用 双指针的思想,这题其实把握了思想还是挺简单的,要保证无重复的的,一般会先想到HashSet,可以保证数组的字符的唯一性。 
设置一左一右两个指针,每次我们都移动右指针,如果右边的指针中的元素在Set中存在了,那么就要开始根据已经存在的元素移动左边指针了。同时我们要把左右指针里面的元素所在的索引值(index)给保存下来。 
代码还是很好理解的:

show the code

 1 public int lengthOfLongestSubstring(String s) {
 2     if (s.length() == 0) return 0;
 3     Set<Character> set = new HashSet<>();
 4     LinkedList<Integer> list = new LinkedList<>();
 5     char[] charsArray = s.toCharArray();
 6     int left = 0;
 7     int res = 0;
 8     for (int right = 0, len = charsArray.length; right < len; ++right) {
 9         if (set.contains(charsArray[right])) {
10             res = Math.max(res, right - left);
11             while (set.contains(charsArray[right])) {
12                 int index = list.removeFirst();
13                 set.remove(charsArray[index]);
14             }
15             list.addLast(right);
16             left = list.getFirst();
17             set.add(charsArray[right]);
18         } else if (right == len - 1) {
19             res = Math.max(res, right - left + 1);
20         } else {
21             set.add(charsArray[right]);
22             list.addLast(right);
23         }
24     }
25     return res;
26 }

时间复杂度O(n),空间复杂度O(n)。

 

转载于:https://www.cnblogs.com/jamesmarva/p/11260007.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值