LeetCode 003 Longest Substring Without Repeating Characters - Java

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.

 

定位:中等题

对给出的字符串,求出其中不出现重复字母的最大长度的字串,该问题以O(n)的时间复杂度解决。基本思路为,用两个标志位,first与second,首先first至于首,second往后扫,经过的每个字符都存储记录,一旦出现重复的,second就停止,将first向后移动到当前出现重复的字母前一次出现位置的后一位,过程中经过位置的字母都在存储结构中删去。然后继续移动second,重复上述过程,一直到second扫完字符串结束。

 

Java实现:

 1 import java.util.HashSet;
 2 import java.util.Set;
 3 
 4 public class Solution {
 5     public int lengthOfLongestSubstring(String s) {
 6         int len=s.length();
 7         if(len==0){
 8             return 0;
 9         }
10         int i=0,j=0;
11         int maxLen=1,Len=1;
12         Set set=new HashSet<Character>();
13         j++;
14         set.add(s.charAt(i));
15         while (j<len){
16             if(!set.add(s.charAt(j))){
17                 while (s.charAt(i)!=s.charAt(j)){
18                     set.remove(s.charAt(i));
19                     i++;
20                 }
21                 if(i!=j){
22                     i++;
23                 }
24             }else{
25                 set.add(s.charAt(j));
26             }
27             Len=j-i+1;
28             if(Len>maxLen){
29                 maxLen=Len;
30             }
31             j++;
32         }
33         return maxLen;
34     }
35 }
posted @ 2017-06-03 23:01  仰恩  阅读(177)  评论(0编辑  收藏  举报