[LeetCode] Longest Substring Without Repeating Characters

用left、right两个指针(用的是数字,当成指针来理解)在String上移动。

每次迭代判定right指向的字符ch是否存在于HashMap中:

    如果不存在,把这个字符作为key,位置作为值加入HashMap,right向右移动一格,尝试更新最大长度max;

    如果存在,用ch作为key找到已存在字符的位置i,把left一步一步移动到i+1位置,途径的元素从HashMap删掉。

class Solution {
    public int lengthOfLongestSubstring(String s) {
		int ans = 0, left = 0, right = 0;
		HashMap<Character,Integer> map = new HashMap<Character,Integer>(s.length());
		while(right < s.length()) {
			char ch = s.charAt(right);
			if(!map.containsKey(ch)) {
				map.put(ch,right);
				++right;
				ans = Math.max(ans, map.size());
			}else {
				int index = map.get(ch);
				while(left < index+1) {
					map.remove(s.charAt(left));
					++left;
				}
				//此时left == map.get(ch)+1;
				map.remove(ch);
			}
		}
		return ans;
    }
}

但是这样太慢,想了一下,HashSet就够了。

每次判断一下right指向的字符是否存在于HashSet中,相应地把left或right向左移动,宏观上看同样是左右指针只在数组上走一遍。

修改后时间减少了10ms这样。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int ans = 0, left = 0, right = 0;
		HashSet<Character> table = new HashSet<Character>();
		while(right < s.length()) {
			if(!table.contains(s.charAt(right))) {
				table.add(s.charAt(right));
				++right;
				ans = Math.max(ans, table.size());
			}else {
				table.remove(s.charAt(left));
				++left;
			}
		}
		return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值