leetcode 3. 无重复字符的最长子串(Longest Substring Without Repeating Characters)

博客围绕无重复字符的最长子串问题展开,给出英文和中文题目描述及示例。解题思路采用双指针和查找表,当遇到第二个相同字符时,遍历前面数组,将该字符首次出现位置之前的字符从表里删除,以保证子串的连续性。

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

无重复字符的最长子串

 

题目(Medium)

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.

给定一个字符串,找出不含有重复字符的 最长子串 的长度。

示例:

给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。

给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。

给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。


 

原题链接

 

 

思路:

双指针,查找表,当遇到个第二个相同的字符时,就遍历前面p到i-1的数组,把第二个相同的字符出现的第一个位置之前的字符都在表里删掉,因为要断开了嘛,此时不连续了

 

import java.util.HashSet;
import java.util.Scanner;

public class 无重复字符的最长子串 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.next();
		System.out.println(lengthOfLongestSubstring(s));
		
	}
	
    public static int lengthOfLongestSubstring(String s) {
		char[] ch = s.toCharArray();
		HashSet<Character> set = new HashSet<>();
		int n = ch.length;
		int max=0;
		int sum=0;
		int p=0;
		for(int i=0;i<n;i++)
		{
			if(!set.contains(ch[i]))
			{
				set.add(ch[i]);
				sum++;
			}
			else
			{
				max = Math.max(max,sum);
				for(;p<i;p++)
				{
					if(ch[p]!=ch[i])
					{
						set.remove(ch[p]);
//						System.out.println(p+" "+set.toString());
					}
					else
					{
						p++;		
						break;
					}
				}
				
				sum=i-p+1;
//				sum=set.size(); //记录sum都是对的,但这个性能差一些,因为调用了内部方法嘛
			}
		}
		max = Math.max(max,sum);
		
		return max;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值