[LeetCode 003] Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

  • 设置两个pointerstart指向子串的起始位置,end指向子串的终止位置。
  • 设置一个HashMap,保存字符和该字符出现的在字符串中的位置。
  • HashMap中已经存在某个字符,并且该字符在字符串中出现的位置在start之后,说明出现了重复字符。
    • 更新最大子串的长度max
    • 更新HashMap中该重复字符出现在字符串的位置,即end

Implementation

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int start = 0;
        int max = 0;
        for (int end = 0; end < s.length(); end++) {
            char ch = s.charAt(end);
            if (map.containsKey(ch) && map.get(ch) >= start) {
                max = (max < end - start? end - start: max);
                start = map.get(ch) + 1;
            }
            map.put(ch, end);
        }
        return max < s.length() - start? s.length() - start: max;
    }

}
posted @ 2016-02-16 15:06  VicHawk  阅读(106)  评论(0编辑  收藏  举报