Longest Substring Without Repeating Characters

来源:互联网 发布:苏州文荟人才公寓网络 编辑:程序博客网 时间:2024/04/28 18:33

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

感觉还是需要把英语练一下,要不然面试的时候会紧张...


这道题是开学时候做的,应该说印象不深了,但是想了一下应该就是hashmap没跑了,只不过重点在于如何更新hashmap。

思路: 用两个指针pre, cur 表示当前维护的最长的不重复的子串 。 遍历字符串s, 对于当前的char字符,如果存在于hashmap,那么可能需要更新pre的下标。如果在hashmap中查出来的值要>= pre的位置的时候,这个时候要更新pre = index+1;在=的时候也需要更新,原因是在计算长度的时候pre这个位置的值也是计算进去的,如果重复的值是pre对应的这个字符,那么也是需要更新的。


代码l;

public int lengthOfLongestSubstring(String s) {        if(s == null || s.length() == 0) return 0;        HashMap<Character, Integer> map = new HashMap<>();        int max = Integer.MIN_VALUE;        int pre = 0;        int cur = 0;        while(cur<s.length()){            if(!map.containsKey(s.charAt(cur))){                map.put(s.charAt(cur), cur);            }else{                int index = map.get(s.charAt(cur));                if(index>=pre){                    pre = index+1;                }                map.put(s.charAt(cur), cur);            }            max = Math.max(cur-pre+1, max);            cur++;        }        return max;    }


0 0
原创粉丝点击