LeetCode-Longest Substring Without Repeating Characters

本文介绍了一种经典的字符串处理问题——寻找最长无重复字符子串,并提供了两种解法:暴力破解法和滑动窗口法。通过这两种方法,读者可以了解到解决此类问题的基本思路。

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

Description:
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.

题意:找出一个字符串中连续的且每个字符都只出现一次的子串;

第一种解法:最简单的方法就是暴力破解,遍历所有的可能,找出最大长度的那个;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;//最大长度变量
        for(int i=0; i<s.length(); i++){
            String str = "" + s.charAt(i);//不重复连续子串
            for(int j=i+1; j<s.length(); j++){
                if(str.indexOf(s.charAt(j)) != -1){
                    break;
                }
                str += s.charAt(j);
            }
            maxLen = str.length() > maxLen ? str.length() : maxLen;
        }
        return maxLen;
    }
}

第二种解法:我们采用滑动窗口的思想,定义区间[st, ed)为连续不重复字符的子串,当下个一字符在子串中不重复时,我们移动端点ed向右;当下一个字符在子串中重复时,我们移动端点st向右,直到不存在与下个字符相同的字符为止;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        Set<Character> table = new HashSet<>();
        int st, ed;//区间端点
        st = ed = 0;
        while(ed < s.length()){
            if(table.contains(s.charAt(ed))){
                table.remove(s.charAt(st++));
            }
            else{
                table.add(s.charAt(ed++));
                maxLen = ed-st > maxLen ? ed-st : maxLen;
            }
        }
        return maxLen;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值