Monday, November 30, 2015

[leetcode]Longest Substring Without Repeating Characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        int start = 0;
        int longest = 0;
        HashMap<Character, Integer> lookup = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++){
            char cur = s.charAt(i);
            if (lookup.containsKey(cur) && lookup.get(cur) >= start){
                start = lookup.get(cur)+1;
            }
            lookup.put(cur, i);
            longest = Math.max(longest, i-start+1);
        }
        return longest;
    }
}

No comments:

Post a Comment