【LeetCode從零單排】No 3 Longest Substring Without Repeating Characters

李博Garvin發表於2015-03-17

題目

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

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



相關文章