Longest Substring Without Repeating Characters

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.

最直接解决办法就是设置两个指针扫描字符串,如果碰到重复的跳到外循环下一个位置继续扫描,这样复杂度为O(n^2),简单动手发现这种实现做了很多重复工作。后面进行优化。

 

import java.util.Hashtable;
public class Solution {
    	public int lengthOfLongestSubstring(String s) {
		int MaxLen = 0;
		Hashtable<Character, Integer> tb = new Hashtable<>();
		int count = 1;
		for(int i=0;i<s.length();i++){
			tb.clear();
			tb.put(s.charAt(i), 1);
			count = 1;
			for(int j=i+1;j<s.length();j++){
				if(!tb.containsKey(s.charAt(j))){
					tb.put(s.charAt(j), 1);
					count ++ ;
				}else {
					break;
				}
			}
			if(count > MaxLen){
				MaxLen = count;
			}
		}
		return MaxLen;
	}
}


优化时间复杂度的方法:我们可以考虑只扫描母串,直接从母串中取出最长的无重复子串。

对于s[i]:

1.s[i]没有在当前子串中出现过,那么子串的长度加1;

2.s[i]在当前子串中出现过,出现位置的下标为j,那么新子串的起始位置必须大于j,为了使新子串尽可能的长,所以起始位置选为j+1。

public int lengthOfLongestSubstring2(String s){
		int maxLen = 0;
		//记录子串前一位置的下标,初始为-1
		int index = -1;
		//记录字符在s中出现的位置。
		int [] loca = new int[256];
		Arrays.fill(loca, -1);
		for(int i=0;i<s.length();i++){
			char c = s.charAt(i);
			//如果c出现了,更新index 为c上一次出现位置
			if(loca[c] > index){
				index = loca[c];
			}
			// 更新最大长度
			if(i-index>maxLen){
				maxLen = i-index;
			}
			loca[c] = i;
		}
		return maxLen;
	}


时间对比如下图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值