3.Longest Substring Without Repeating Characters

leetcode link

Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:
Input: s = ""
Output: 0

思路:

用前后两个指针表示字符串中子串的一个滑动窗口
右指针一直往前走,并把遍历过的每一个字符以及index都放入HashMap中,左指针根据当前右指针对应的字符是否出现过而调整位置(取靠右的位置);
每遍历一个字符后判断更新最长不重复子串的最大值。

注意:

1.字符串长度为0时;
2.若字符在前面出现过,则取出现过的index+1与当前的左指针作比较;
3.若左右指针都是 从0开始,则长度为right-left+1;若左从0开始,右从1,则为right-left;

你可能感兴趣的:(3.Longest Substring Without Repeating Characters)