3. Longest Substring Without Repeating Characters

Question:

Find the longest sub-string without repeating characters. For example, if the given string is "abcdcefg", the longest sub-string is "dcefg".

Analysis:

In order to check whether the character repeats or not, the common approach is to build a hash table, when the character appears, we set its value in the hash table to be 0, therefore, when that character appears again, we know the sub-string will have duplicated character if we continue.

When continue with new sub-sting, we should set the hash table value of the previous characters to be 0. Each time we we encounter a duplicated character, a new sub-string begins.

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String T) {
 3         if (T == null || T.length() == 0) return 0;
 4         Set<Character> set = new HashSet<>();
 5         int begin = 0, maxLength = -1;
 6         
 7         for (int i = 0; i < T.length(); i++) {
 8             if (!set.contains(T.charAt(i))) {
 9                 maxLength = Math.max(maxLength, i - begin + 1);
10                 set.add(T.charAt(i));
11             } else {
12                 while (T.charAt(begin) != T.charAt(i)) {
13                     set.remove(T.charAt(begin));
14                     begin++;
15                 }
16                 // we don't need to remove from set as we already
17                 // passed that letter
18                 begin++;
19             } 
20         }
21         return maxLength;  
22     }
23 }

 

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        existed = set()
        max_length = 0
        start = 0
        for end in range(len(s)):
            while s[end] in existed:
                existed.remove(s[start])
                start += 1
            existed.add(s[end])
            max_length = max(max_length, end - start + 1)
        return max_length

 

posted @ 2015-01-26 05:50  北叶青藤  阅读(202)  评论(0)    收藏  举报