3. Longest Substring Without Repeating Characters java solutions

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int n = s.length();
 4         int begin = 0, end = 0;
 5         boolean[] exist = new boolean[256];
 6         int maxlen = 0;
 7         while(end < n){
 8             if(!exist[s.charAt(end)]){
 9                 exist[s.charAt(end)] = true;
10                 end++;
11             }else{
12                 while(s.charAt(begin) != s.charAt(end)){
13                     exist[s.charAt(begin)] = false;
14                     begin++;//下一次搜寻,应该跨过出现重复的地方进行,否则找出来的候选串依然有重复字符,且长度还不如上次的搜索。
15                 }
16                 begin++;
17                 end++;
18             }
19             maxlen = Math.max(maxlen,end-begin);
20         }
21         return maxlen;
22     }
23 }

使用begin和end两个下标来记录最长子串的开始和结束位置。时间复杂度O(n)

 

posted @ 2016-06-28 14:06  Miller1991  阅读(109)  评论(0编辑  收藏  举报