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.


一开始的思路:逐位扫描,将每位的字符与下标存到HashMap中,遇到重复字符时,计算map长度,从map中取出重复字符前一次出现时的下标,同时清空map。

从取出的下标的下一位开始重复上一过程。

当余下的字符串长度目前小于已知的最大长度时就不必再往后扫描了。

代码如下:

public class Solution {
	public int lengthOfLongestSubstring(String s) {
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		int longest = 0;	
		if(s != null){
			for(int i = 0; i < s.length(); i++){
				char c = s.charAt(i);
				if(!map.containsKey(c)){
					map.put(c,i);
					if(map.size() > longest){
						longest = map.size();
					}
				}else{
					if(map.size() > longest){
						longest = map.size();
					}
					i = map.get(c);
					if(s.length()-1-i <= longest){
						break;
					}
					map.clear();
				}
			}
		}
		return longest;
	}
}


该方案提交时在遇到字符串长度很长时会出现运行时间过长,原因在于每次遇到重复值时都需要重新构建map。



参考其他人的方案后使用新的思路:

不再清空map重构,记录当前子串开始时的下标,遇到重复字符时就更新map中重复字符的下标值。

如果重复的字符是在当前子串开始位置之前的,则只更新map就行,否则说明当前子串中出现了重复的字符,需要同时更新子串开始下标。

子串的长度就是当前下标与开始下标的差值+1.

此方案Accepted,代码如下:

public class Solution {
	public int lengthOfLongestSubstring(String s) {
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		int longest = 0;	
		if(s != null){
			for(int i = 0, start = i; i < s.length(); i++){
				char c = s.charAt(i);
				if(map.containsKey(c)){
					start = Math.max(start, map.get(c)+1);
				}
				map.put(c,i);
				longest = Math.max(longest, i-start+1);
			}
		}
		return longest;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值