美文网首页
leetcode——双指针/滑动窗口

leetcode——双指针/滑动窗口

作者: 雅芳 | 来源:发表于2018-09-20 11:42 被阅读7次

1.无重复字符的最长子串

题目描述
给定一个字符串,找出不含有重复字符的最长子串的长度。
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
思路
用滑动窗来记录当前子串范围。max记录最大长度。
为了快速找到上次出现的字符,用map来保存出现的字符和它对应的位置(也可以用一个长度256的数组表示所有字符位置)。出现重复字符时需要更新。值得注意的时,更新时要判断left和index+1的相对位置,以免发生left左移情况。
标准ascii码表127个,扩展ASCII 字符是从128 到255(0x80-0xff)的字符。

import java.util.HashMap;
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s==null)return 0;
        int start=0;
        int end = 0;
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        int max = 0;
        for(int i=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i))){
                max = (end-start)>max?(end-start):max;
                //这里做判断,以免start左移
                int firstOccur = map.get(s.charAt(i))+1;
                start = firstOccur>start?firstOccur:start;
            }
            map.put(s.charAt(i),i);
            end++;
        }
        max = (end-start)>max?(end-start):max;
        return max;
    }
}

相关文章

网友评论

      本文标题:leetcode——双指针/滑动窗口

      本文链接:https://www.haomeiwen.com/subject/jjignftx.html