Wednesday, July 16, 2014

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


 public class Solution {  
   public int lengthOfLongestSubstring(String s) {  
     if (s == null || s.isEmpty())  
       return 0;  
     int len = s.length();  
     boolean[] table = new boolean[256];  
     int start = 0;  
     int maxLength = 1;  
     int i = 0;  
     while (i < s.length()) {  
       char curr = s.charAt(i);  
       if (!table[curr])  
         table[curr] = true;  
       else {  
         int currLen = i - start;  
         maxLength = Math.max(maxLength, currLen);  
         for (int j=start; j<i; j++) {  
           if (s.charAt(j) == s.charAt(i)) {  
             start = j+1;  
             break;  
           }  
           else  
             table[s.charAt(j)] = false;  
         }  
       }  
       i++;  
     }  
     maxLength = Math.max(maxLength, len-start);  
     return maxLength;  
   }  
 }  
Note:这里关键是看到如何处理else中update完maxLength之后的部分

No comments:

Post a Comment