Fork me on github

无重复字符的最长子串

无重复字符的最长子串

思路

总体的思路是滑动窗口,可以借助哈希表将这些字符所在位置都记录起来,以便统计不重复子串的长度。

代码

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() <= 0){
            return 0;
        }

        char[] strs = s.toCharArray();
        //把这些字符出现的位置存储在哈希表中
        Map<Character, Integer> Position = new HashMap<>();
        for(char c : s.toCharArray()){
            Position.put(c, -1);
        }

        int maxLen = 0;
        int curLen = 0;
        for(int i = 0; i < s.length(); i++){
            //prePos是该字符上次出现的位置
            int prePos = Position.get(strs[i]);
            //如果没有出现过或者新出现的字符能够使用这个不重复序列增长
            if(prePos < 0 || i - prePos > curLen){
                curLen++;
            }
            else{
                maxLen = Math.max(maxLen, curLen);
                curLen = i - prePos;
            }
            Position.put(strs[i], i);
        }
        maxLen = Math.max(maxLen, curLen);
        return maxLen;
    }
}
posted @ 2020-07-26 23:08  zjy4fun  阅读(153)  评论(0编辑  收藏  举报