Longest Substring Without Repeating Characters

来源:互联网 发布:java的弱引用 编辑:程序博客网 时间:2024/06/03 23:57

static class Solution {

    public static int lengthOfLongestSubstring(String s) {        if (s== null || s.length() == 0) {            return 0;        }        /**         *         * 思路:求不包含重复元素的最大字串,其实核心就是要找到最大子串的起始以及结束位置         *         * 1。start记录字段的起始位置         *  end记录子串的结束位置         *  map的键用来保存字符,值保存该字符的位置         * 1.将字符依次放入map中         * 2.判断该map是否含有该字符         *      是:寻找起始位置         *      否:结束位置为当前位置,index也记住当前位置         * 3.根据start,end找到最大字串         */        Map<Character,Integer> map = new HashMap<>();        char[] chars = s.toCharArray();        int maxLength = 0;        int start = 0;        int end = 0;        for (int i = 0;i< chars.length;i++) {            if (map.containsKey(chars[i])) {                if (i - map.get(chars[i]) > 1) {                    if (map.get(chars[i])+1 > start) {                        start = map.get(chars[i])+1;                    }                }else {                    start = i;                }            }            end = i;            int subLenen = end - start+1;            if (subLenen > maxLength) {                maxLength = subLenen;            }            map.put(chars[i],i);        }        return maxLength;    }
原创粉丝点击