3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.

方法:Sliding Window + Hashmap

思路:模拟变长滑动窗的方式,窗的起末位置定义为[i, j],滑动窗保持其中没有repeating的字符,持续forward滑动遍历,若前方出现重复字符,则窗尾更新(跟进)直到窗中没有repeating字符(利用map找位置),过程中记录滑动窗的最大长度作为结果。
具体:
在遍历(j++)的过程中,实时将每个字符的最新位置保存到map中,char -> pos,
并且在过程中:
a. 若碰到map中出现过的字符x,为保持窗中没有Repeating字符,从map取出之前最近出现过的字符x位置pos,窗的起始位置i跟上,更新到pos + 1;
b. 碰到map没有字符,无特殊处理;
c. 每次计算当前窗的长度j - i + 1,若大 则更新max_length。

Time Complexity: O(N)
Space Complexity: O(N)

Example:
str = "abcdefc.."
例: j遍历到c之前,"[abcdef]..",遇到c变为:"abc[defc].."

class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        HashMap<Character, Integer> map = new HashMap<>();
        
        int max_sublength = 0;
        
        int left = 0;
        for(int right = 0; right < s.length(); right++) {
            if(map.containsKey(s.charAt(right)) && map.get(s.charAt(right)) >= left) {
               left = map.get(s.charAt(right)) + 1;
            }
            map.put(s.charAt(right), right);
            
            if(right - left + 1 > max_sublength) {
                   max_sublength = right - left + 1;
            }
        }
        
        return max_sublength;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容