标签:
1 题目
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.
Hash Table Two Pointers String
public int lengthOfLongestSubstring(String s) { Hashtable<Character,Integer> hash=new Hashtable<>(); int length=s.length(); int max=0; int availablefrom=0; for(int i=0;i<length;i++){ if(hash.containsKey(s.charAt(i))){ //int last = the largest index where has the same character (before current index i) int last=(Integer) hash.get(s.charAt(i)); //int available-from = the next index from where latest duplication ends (before current index i) //之所以取最大,防止出现abba,遍历到第二个a时,last会比availableform小 availablefrom=Math.max(availablefrom, last+1); } //then the possible substring is located between available-from and i。 max=Math.max(max, i-availablefrom+1); hash.put(s.charAt(i),i); } return max; }
[Leet code 3]Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4432719.html