leetcode#3-Longest Substring Without Repeating Characters-java

本文探讨了如何找出字符串中最长的无重复字符子串及其长度。提供了三种解法,包括使用队列、集合以及动态规划的方法。这些解法不仅展示了不同的数据结构应用,还深入分析了每种方法的时间复杂度。

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

题目:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

解法一:

Tips:
使用queue来存储,方便在出现重复元素时,对元素进行删除,并不影响顺序
有一个点需要主要,在判断到重复元素时,进行poll操作,记得再把重复元素重新加入。

int result = 0;
Queue<Character> queue = new LinkedList<>();
for(int i=0;i<s.length();i++){
    if(queue.contains(s.charAt(i))){
        result = Math.max(result,queue.size());
        while(queue.size()!=0){
            char temp = queue.poll();
            if(temp==s.charAt(i)){
                queue.add(s.charAt(i));
                break;
            }
        }
    }else{
        queue.add(s.charAt(i));
    }
}
return Math.max(queue.size(),result);

解法二:
解法二和解法一的思路一致,但由于使用了set,限制了重复元素,不需使用双重for循环

int i = 0, j = 0, max = 0;
        Set<Character> set = new HashSet<>();
        while (j < s.length()) {
            if (!set.contains(s.charAt(j))) {
                set.add(s.charAt(j++));
                max = Math.max(max, set.size());
            } else {
                set.remove(s.charAt(i++));
            }
        }

        return max;

解法三:动规思路
由于自己现在还没有对动归有系统的学习
希望过段时间总结之后再来分析,先贴别人的代码

int lengthOfLongestSubstring(string s) {
    // for ASCII char sequence, use this as a hashmap
    vector<int> charIndex(256, -1);
    int longest = 0, m = 0;

    for (int i = 0; i < s.length(); i++) {
        m = max(charIndex[s[i]] + 1, m);    
        // automatically takes care of -1 case
        charIndex[s[i]] = i;
        longest = max(longest, i - m + 1);
    }

    return longest;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值