leetcode做题总结,题目Longest Substring Without Repeating Characters

题目链接Longest Substring Without Repeating Characters

这道题使用了窗口的概念,在有关子字符串的题目中可以考虑,即使用前后两个指针控制一个窗口,窗口里包含的便是这个没有重复字符的子字符串。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0)
            return 0;
        HashSet<Character> set = new HashSet<Character>();
        int max=0;
        int first=0;
        int last=0;
        while(first<s.length()){
            if(set.contains(s.charAt(first))){
                if(max<first-last)
                    max=first-last;
                while(s.charAt(first)!=s.charAt(last)){
                    set.remove(s.charAt(last));
                    last++;
                }
                if(last!=first)
                    last++;
                first++;
            }else{
                set.add(s.charAt(first));
                first++;
            }
        }
        if(max<first-last)
            max=first-last;
        return max;
    }
}

Update 2015/08/31: 下面的思路和上面的一样。只是用boolean数组代替HashSet来储存子串不同的字符,当下一个字符和窗口里的有重复是,缩短窗口

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s==null)
            return 0;
	boolean[] flag = new boolean[256];
 
	int result = 0;
	int start = 0;
	char[] arr = s.toCharArray();
 
	for (int i = 0; i < arr.length; i++) {
		char current = arr[i];
		if (flag[current]) {
			result = Math.max(result, i - start);
			// the loop update the new start point
			// and reset flag array
			// for example, abccab, when it comes to 2nd c,
			// it update start from 0 to 3, reset flag for a,b
			for (int k = start; k < i; k++) {
				if (arr[k] == current) {
					start = k + 1; 
					break;
				}
				flag[arr[k]] = false;
			}
		} else {
			flag[current] = true;
		}
	}
 
	result = Math.max(arr.length - start, result);
 
	return result;
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值