(LeetCode) 3、Longest Substring Without Repeating Characters

本文介绍了一种寻找字符串中最长无重复字符子串的方法,通过遍历并使用哈希集合记录字符出现的位置来实现。提供了两种解决方案,一种是简单直接的方式,另一种是优化后的滑动窗口方法。

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

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.

思路:

从位置begin开始,一直找到end, str[end+1]为[begin, end]中的某个字符重复,即从begin开始,最大不重复字符子串长度为end - begin;

判断字符是否存在某个字符集中,暂时只想到 set

代码:

public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        Set<Character> set = new HashSet<Character>();
		for(int i = 0; i < n; i++){
			if(n - i < ans) break; //剩余字符没有ans大,不需计算
			set.clear();
			for(int j = i; j < n; j++){
				char c = s.charAt(j);
				if(set.contains(c)){
					ans = Math.max(ans, j - i);
					break;
				}
				else
					set.add(c);
			}
			ans = Math.max(ans, set.size());
		}
        return ans;
    }

 优化:

假设[x, y]为从x开始的最大无重复字符子串,str[y+1]与[x, y]中的某个字符重复,可以肯定从[x+1, y]是没有重复字符的,如果有的话,在[x, y]的过程中就会出现,

所以从x+1位置开始,只需要set.remove(str[x]), 从y+1开始计算,set中的值就没有必要clear()

代码:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        int pre = 0;
        Set<Character> set = new HashSet<Character>();
		for(int i = 0; i < n; i++){
			if(n - i < ans) break; //剩余字符没有ans大,不需计算
			if(i > 0) set.remove(s.charAt(i-1));
			while(pre < n){
				char c = s.charAt(pre);
				if(set.contains(c))
					break;				
				else
					set.add(c);
				pre++;
			}
			ans = Math.max(ans, set.size());
		}
        return ans;
    }
}

 

 

转载于:https://www.cnblogs.com/IwAdream/p/5521908.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值