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

本文探讨了三种不同的算法来寻找字符串中最长的无重复字符子串长度,包括原始的遍历检查法、使用HashSet优化的窗口机制以及利用HashMap实现的高效解决方案。

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

我的代码一开始没有考虑字符串为空的特殊情况

public class Test {


    public static int lengthOfLongestSubstring(String s) {
        int longest=0;   //latest char index+1
            byte[] b = s.getBytes();
            int l = b.length;
            byte[] temp = new byte[l];
            for (int i = 0; i < l; i++) {
                temp[0]= b[i]; //start char
                int end=1;
                for (int j=i+1;j<l;j++) {
                    //check b[j] is exist in temp[]
                    boolean isExist=false;
                    for (int k=0;k<end;k++) {
                        if (temp[k] == b[j]) {
                            isExist=true;
                        }
                    }
                    if (isExist == false) {
                        temp[end] = b[j];
                        end++;
                    } else {
                        break;
                    }
                }
                longest=(longest>end)?longest:end;
                if (longest>l-i-1) {
                    break;
                }
            }
            return longest;
    }

    public static void main(String[] args) {
        String s1 = "bbbbb";
        String s2 = "abcabcbb";
        String s3 = "pwwkew";
        int r1 = lengthOfLongestSubstring(s1);
        int r2 = lengthOfLongestSubstring(s2);
        int r3 = lengthOfLongestSubstring(s3);
        System.out.println("r1 = " + r1);
        System.out.println("r2 = " + r2);
        System.out.println("r3 = " + r3);
    }
}

官方答案2:窗口机制,运用了hashSet,速度加快;

  public static int lengthOfLongestSubstring2(String s) {
        int l = s.length();
        HashSet<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < l && j < l) {
            if (!set.contains(s.charAt(j))) {
                set.add(s.charAt(j++));
                int t = j - i;
                ans = (ans > t) ? ans : t;
            } else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }

官方答案3:两个字,厉害

public class Solution {
    public int lengthOfLongestSubstring(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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值