【leetcode】3. Longest Substring Without Repeating Characters

计算最长的无重复字符的串长

用HashMap记住重复的单词及其位置。当重复时,让tempStart指针移到重复位置+1,如果start指针小于tempStart,则更新start指针,长度就是当前重复的位置 - start。读到字符串末尾时还需要判断一次

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int start = 0;
        int maxLength = 0;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                int length = i - start;
                int tempStart = map.get(c) + 1;
                start = start > tempStart ? start : tempStart;
                if (maxLength < length) {
                    maxLength = length;
                }
            }
            map.put(c, i);
        }
        int length = s.length() - start;
        if (maxLength < length) {
            maxLength = length;
        }
        return maxLength;
    }
}
原文地址:https://www.cnblogs.com/lanhj/p/5373674.html