LeetCode(3)Longest Substring Without Repeating Characters

本文探讨了如何寻找给定字符串中最长不重复子串的问题,并提供了两种算法实现方案:暴力搜索与滑动窗口法。前者通过遍历所有可能的子串来查找,而后者则采用更高效的动态调整窗口大小策略。
题目


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.

翻译一下就是:给定一个字符串,找到最长不重复字符串的长度

例如:给定“pwwkew”,答案是“wke”,长度是3,而不是“pwke”,因为“pwke”是子序列,而不是子字符串

思路


最直接能够想到的方法,遍历所有的子字符串,写一个方法,如果这个子字符串中没有重复的字符,那么返回true,记录这个字符串的长度,随时更新

找到所有的子字符串就需要两层循环,时间复杂度就是O(n^2),时间复杂度有些高

代码


public class method1 {
    public int lengthOfLongestSubstring(String s){
        int n=s.length();
        int ans=0;
         for (int i = 0; i < n; i++)
                for (int j = i + 1; j <= n; j++)
                    if (allUnique(s, i, j)) 
                        ans = Math.max(ans, j - i);
            return ans;
    }

    public boolean allUnique(String s, int start, int end) {
        Set<Character> set = new HashSet<>();
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) 
                return false;
            set.add(ch);
        }
        return true;
    }
}
思路优化


这里写图片描述

所以,解决方案中给出了一种滑动窗口的方法

滑动窗口是数组和字符串问题中常用的抽象概念。窗口是数组/字符串中通常由开始和结束索引定义的一系列元素,即 [i,j)(左闭合,右开放)。

    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))) {
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            } else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }

滑动过程,如下图所示:

这里写图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值