首页 > 其他 > 详细

无重复字符的最长子串

时间:2019-05-03 12:48:31      阅读:123      评论:0      收藏:0      [点我收藏+]
//方法一:使用HashMap记录字符的位置,实现滑动窗口
public class LengthOfLongestSubstring {
public int lengthOfLonggestSubstring(String s) {
if(s == null) {
            throw new IllegalArgumentException();
        }else {
            Map<Character, Integer> map = new HashMap<>();
            char ch = ‘ ‘;
            int maxLen = 0;
            int subIndex =0;
            for(int i=0; i < s.length(); i++) {
                ch = s.charAt(i);
                if(!map.containsKey(ch)) {
                    map.put(ch, i);
                    maxLen = Math.max(maxLen, i - subIndex + 1);
                }else {
                    //若出现重复字符,判断重复字符索引是否大于当前开始索引,若是,则将左侧开始索引更改为重复字符后一位
                    subIndex = Math.max(map.get(ch) + 1, subIndex);
                    //更改重复字符索引为新的位置
                    map.put(ch, i);
                    //如果重复字符索引小于当前开始索引,字符串长度会加1,否则得到的结果比实际值小1
                    maxLen = Math.max(maxLen, i - subIndex + 1);
                }
            }
            return maxLen;
        }
    }
}
//方法二:
public int lengthOfLonggestSubstring(String s) {
        if(s == null) {
            throw new IllegalArgumentException();
        }else if(s.equals("")) {
            return 0;
        }else {
            Set<Character> set = new HashSet<>();
            int i=0;
            int j=0;
            int len = s.length();
            int maxLen = 0;
            while(i < len && j < len) {
                if(!set.contains(s.charAt(j))) {
                    set.add(s.charAt(j));
                    j++;
                    maxLen = Math.max(maxLen, j-i);
                }else {
                    //可以确定出现重复字符后的重新开始的位置,比如abcbad,出现重复的b后,会删除最开始的ab,
                    //从c开始
                    set.remove(s.charAt(i));
                    i++;
                }
            }
            return maxLen;
        }    
}

 

 

 

无重复字符的最长子串

原文:https://www.cnblogs.com/xiyangchen/p/10804681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!