字符串——最长无重复子串

来源:互联网 发布:mac终端如何输入密码 编辑:程序博客网 时间:2024/05/29 08:35


转自:https://discuss.leetcode.com/topic/8232/11-line-simple-java-solution-o-n-with-explanation


the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.

public int lengthOfLongestSubstring(String s) {        if (s.length()==0) return 0;        HashMap<Character, Integer> map = new HashMap<Character, Integer>();        int max=0;        for (int i=0, j=0; i<s.length(); ++i){            if (map.containsKey(s.charAt(i))){                j = Math.max(j,map.get(s.charAt(i))+1);            }            map.put(s.charAt(i),i);            max = Math.max(max,i-j+1);        }        return max;    }


原创粉丝点击