Leetcode 3. Longest Substring Without Repeating Characters

12 篇文章 0 订阅
3 篇文章 0 订阅

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.

method 1 sliding window

使用hashSet记录某个字符是否出现过

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

但是,我们可以对该方法进行优化,我们可以跳过那些已经确定无重复字符的区间,因此使用map替代set,map的value表示key的所在位置

method 2 Sliding Window Optimized

int lengthOfLongestSubstring(string s) {
	map<char, int> map;
	int maxLength = 0;
	int left = 0, right = 0;

	while (right < s.size()){
		char ch = s[right];
		if (!map.count(ch))
			map[ch] = right;
		else{
			maxLength = max(right - left, maxLength);
			if (left <= map[ch])
				left = map[ch] + 1;
			map[ch] = right;
		}
		right++;
	}

	return max(maxLength, right - left);
}

以下为官方solution的简化版

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

以下是借用上一篇文章中提到的模板所模仿的代码
重点要理解counter的作用,counter表示在区间内重复的字符,因此一旦counter大于0,那么就要移动左指针,缩小窗口

int lengthOfLongestSubstring(string s) {
	vector<int> map(128, 0);
	int counter = 0, begin = 0, end = 0;
	int d = 0;
	while (end < s.size()){
		if (map[s[end++]]++ > 0) counter++;
		while (counter > 0){
			if (map[s[begin++]]-- > 1) counter--;
		}

		d = max(d, end - begin);
	}

	return d;
}

summary

  1. Sliding Window思想,左指针contract window,去除不符合要求的字符,右指针expand window。
  2. 使用counter计数重复的字符数,一次来作为左指针移动的指标,值得借鉴
  3. 使用vector代替map
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值