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

【leetcode刷题笔记】Longest Substring Without Repeating Characters

时间:2014-07-23 16:19:41      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   re   

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.


 

题解:贪心算法。

利用一个hashmap存放当前最长的无重substring所包含的元素,变量leftbound存放当前的最左边界。则当前遍历的字符s[i]有两种情况:

  1. s[i]所指的元素已经存在在map中了,那么就左移leftbound直到leftbound到i这一段不再包含s[i],并且在map中清除leftbound扫过的元素;
  2. s[i]所指的元素不在map中,保持leftbound不动,查看是否需要更新当前最长substring的长度。

代码如下:

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if(s == null || s.length() == 0)
 4             return 0;
 5             
 6         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 7         int leftebound = 0;
 8         int answer = 0;
 9        
10         for(int i = 0;i < s.length();i++){
11             char current = s.charAt(i);
12             if(map.containsKey(s.charAt(i))){                
13                 while(s.charAt(leftebound) != current && leftebound < i){
14                     map.remove(s.charAt(leftebound));
15                     leftebound++;
16                 }
17                 leftebound++;
18             }
19             else {
20                 map.put(current, 0);
21                 answer = Math.max(i-leftebound+1, answer);
22             }
23         }
24         
25         return answer;    
26     }
27 }       

【leetcode刷题笔记】Longest Substring Without Repeating Characters,布布扣,bubuko.com

【leetcode刷题笔记】Longest Substring Without Repeating Characters

标签:style   blog   color   io   for   re   

原文地址:http://www.cnblogs.com/sunshineatnoon/p/3863134.html

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