Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 3. Longest Substring Without Repeating Characters #39

Open
Woodyiiiiiii opened this issue May 1, 2020 · 1 comment
Open

LeetCode 3. Longest Substring Without Repeating Characters #39

Woodyiiiiiii opened this issue May 1, 2020 · 1 comment

Comments

@Woodyiiiiiii
Copy link
Owner

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.

利用滑动窗口法。
定义两个指针代表滑动窗口,两个指针的距离代表定义的字符串长度,并且创建一个HashSet存储字符以便判断字符重复。遍历字符串,如果字符不存在于窗口中,则存入HashSet中,右指针加一;如果存在,左指针加一,并且从HashSet中删除该字符。每次计算更新最长的长度。
注意,如果字符串是“abcdbd”,字符‘b’重复,则左指针加一,把字符'a'剔除了,同时在HashSet中删除了‘a’字符,因为题目要求的是substring,是continuous连续的,所以左指针移动直至删除最先存入的字符‘b’才可。HashSet存的是理想的无重复字符的字符串,窗口长度代表的是HashSet的大小。

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

参考资料:

@Woodyiiiiiii
Copy link
Owner Author

Woodyiiiiiii commented Jan 6, 2022

func lengthOfLongestSubstring(s string) int {
        var l = 0
	var r = 0
	n := len(s)
	res := 0
	charMap := make(map[byte]int)
	for r < n {
		c := s[r]
		if _, ok := charMap[c]; ok {
			for l <= r {
				if s[l] == c {
					l++
					break
				}
				delete(charMap, s[l])
				l++
			}
		}
		res = int(math.Max(float64(res), float64(r-l+1)))
		r++
		charMap[c]++
	}
	return res
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant