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

【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters

时间:2016-02-06 14:11:21      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

题目

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处理方法。是在discuss里看到的,非常巧妙。

代码

public class Solution {
    public int lengthOfLongestSubstring(String s) {
       if(s.length()==0) return 0;
       HashMap<Character,Integer> map=new HashMap<Character,Integer>();
       int max=0;
       for(int i=0,j=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
       }
       return max;
           
   }
    
}


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/bhlsheji/p/5183898.html

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