leetcode 3. Longest Substring Without Repeating Characters

本文探讨了寻找字符串中最长无重复字符子串的问题,提供了两种解决方案:滑动窗口法和哈希表法,详细解释了算法思路及其实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.           
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

思路1:滑动窗口的思想,slow,fast指针来模拟窗口

用HashSet来保存当前最长的不含重复字符的字符串,我们用快指针来判断当前字符是否存在于HashSet中,若不存在,则加入set, 若已经存在,则用slow指针从前开始一出,直到移除重复的字符后,再次加入新的字符。在遍历的过程中,不断的判断更新最长不重复字串的长度

实现1:

public int lengthOfLongestSubstring(String s) {
        int slow=0,fast=0,ret=0;
        HashSet<Character> set=new HashSet<>();
        while(fast<s.length()){
            if(!set.contains(s.charAt(fast))){
                set.add(s.charAt(fast++));
                ret=Math.max(ret,set.size());
            }else {
                set.remove(s.charAt(slow++));
            }
        }
        return ret;
    }

实现2:

和上面思路一样

 public int lengthOfLongestSubstring2(String s) {
        HashSet<Character> set=new HashSet<>();
        int ret=0;
        int tail=0;
        for(int head=0;head<s.length();head++){
            while (tail<=head&&set.contains(s.charAt(head))){
                set.remove(s.charAt(tail++));
            }
            set.add(s.charAt(head));
            ret=Math.max(ret,set.size());
        }
        return ret;
    }

思路2:

用哈希表存储,若存在重复的,则记下重复元素的索引,并在遍历过程中不断更新最大长度。

 public int lengthOfLongestSubstring3(String s) {
        int maxlen=0;
        int tail=-1;//用来记录与当前字符重复的字符所在的索引位置
        HashMap<Character,Integer> map=new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            Character ch=s.charAt(i);
            Integer old=map.get(ch);
            map.put(ch,i);
            if(old!=null&&old>tail){
                tail=old;
            }
            maxlen=Math.max(maxlen,i-tail);
        }
        return maxlen;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值