leetcode--Longest Substring Without Repeating Characters

本文探讨了如何在给定字符串中找到最长的无重复字符子串,提供了两种不同的算法实现,一种使用哈希映射,另一种利用HashSet和StringBuffer。通过具体代码展示了算法的运行过程,帮助读者理解其原理及优化思路。

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

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Code 1: The algorithm is simple and the running time is O(n), where n is the length of the string

public class Solution {
    public int lengthOfLongestSubstring(String s) {
       int max = 0;
		int length = s.length();
		if(length > 0){
			Map<Character, Integer> distinguish = new HashMap<Character, Integer>();
			int startIndex = 0;
			for(int i = 0; i < length; ++i){
				if(distinguish.containsKey(s.charAt(i))) {
					int temp = distinguish.get(s.charAt(i));
				
					for(int j = startIndex; j < temp + 1; ++j)
						distinguish.remove(s.charAt(j));
				
					startIndex = temp + 1;
				}
				distinguish.put(s.charAt(i), i);
				max = Math.max(max, i - startIndex + 1);
			}
		}
		return max;    
    }
}

  

Code 2:

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int len = 0;
 4         HashSet<Character> hset = new HashSet<Character>(); 
 5         if(s.length() > 0){
 6             StringBuffer temp = new StringBuffer();
 7             temp.append(s.charAt(0));
 8             hset.add(s.charAt(0));
 9             ++len;
10             for(int i = 1; i < s.length(); ++i){
11                 if(hset.contains(s.charAt(i))){
12                     StringBuffer abf = new StringBuffer();
13                     abf.append(s.charAt(i));                    
14                     int index = temp.indexOf(abf.toString());
15                     temp.delete(0, index + 1);
16                 }
17                 else
18                     hset.add(s.charAt(i));                
19                 temp.append(s.charAt(i));
20                 if(temp.length() > len)
21                     len = temp.length();
22             }            
23         }
24         return len;
25     }
26 }

 

 

转载于:https://www.cnblogs.com/averillzheng/p/3536686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值