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.

Solution:

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s.length()<2) return s.length();
 4         
 5         int p1=0,p2=1,len=1;
 6         Set<Character> cSet = new HashSet<Character>();
 7         cSet.add(s.charAt(p1));
 8         while (p2<s.length()){
 9             char curChar = s.charAt(p2);
10             if (!cSet.contains(curChar)){
11                 cSet.add(curChar);
12                 p2++;
13             } else {
14                 while (p1<p2 && s.charAt(p1)!=curChar){
15                     cSet.remove(s.charAt(p1));
16                     p1++;
17                 }
18                 if (p1<p2) p1++;
19                 p2++;
20             }
21             
22             if (len<(p2-p1)) len = p2-p1;
23         }
24         
25         return len;
26     }
27 }

 

posted @ 2014-11-28 01:45  LiBlog  阅读(120)  评论(0编辑  收藏  举报