leetcode -- 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.

从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。比如

直到扫描到最后一个字母。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int[] count = new int[26];
 6         /*
 7         for(int i = 0; i < 26; i ++){
 8             
 9         }
10         */
11         resetCount(count);
12         
13         int sLength = s.length();
14         int maxL = 0;
15         int start = 0;
16         for(int i = 0; i < sLength; i++){
17             int index = s.charAt(i) - 97;
18             
19             if(count[index] >= 0){
20                 if(i - start > maxL){
21                     maxL = i - start;
22                 }
23                 // need to backtrack !!!
24                 i = count[index];
25                 start = i + 1;
26                 resetCount(count);
27                 continue;
28             }
29             
30             count[index] = i;
31             
32         }
33         
34         // if last round have no repeating characters, we should check
35         if(maxL < sLength - start){
36             maxL = sLength - start;
37         }
38         return maxL;
39     }
40     
41     public void resetCount(int[] count){
42         for(int i = 0; i < 26; i ++){
43             count[i] = -1;   
44         }
45     }
46 }

ref

http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html

posted @ 2013-06-17 09:41  feiling  阅读(257)  评论(0编辑  收藏  举报