码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Longest Substring Without Repeating Characters

时间:2014-11-28 06:10:44      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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.isEmpty()) return 0;
 4         Set<Character> set = new HashSet<Character>();
 5         int head = 0, end = 1;
 6         set.add(s.charAt(0));
 7         int maxLen = 1;
 8         int curLen = 1;
 9         while (end<s.length()){
10             char cur = s.charAt(end);
11             if (!set.contains(cur)){
12                 set.add(cur);
13                 curLen++;
14                 end++;
15             } else {
16                 while (s.charAt(head)!=cur){
17                     set.remove(s.charAt(head));
18                     curLen--;
19                     head++;
20                 }
21                 head++;
22                 end++;
23             }
24             if (curLen>maxLen) maxLen=curLen;
25         }
26 
27 
28         return maxLen;
29     }
30 }

 

Leetcode-Longest Substring Without Repeating Characters

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4127582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!