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.
Tags: Hash Table ,Two Pointers String
【分析】题目给了Hash Table的提示,问题就很好解决了
<span style="white-space:pre"> </span>设原字符串为S。设置两个指针i,j分别指向当前所找到的符合条件的子串的首尾,i、j之间的每个字符作为key,字符在S中索引在位置作为Value存储在一个HashTable中,取j位置的下一个字符S[j+1]。如果S[j+1]不在HashTable中则将其加入到HashTable中并且j++;若S[index]与S[j]相同则将i到index之间的字符从HashTable中remove掉,然后将i的值设为index,将s[j]加入到HashTable,j++。以此重复进行,直到j=S.length。
T(n) =O(n)
【上码】
<pre name="code" class="java">import java.util.Hashtable;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int longest = 0;
Hashtable curr = new Hashtable();
//int currLen = 0;
char[] chars = s.toCharArray();
int i=0,j=0;
while(j < chars.length){
Object index = curr.get(chars[j]);
if (index==null) {
curr.put(chars[j],j);
j++;
longest = longest>=(j-i)?longest:(j-i);
}
else {
int p = (int)index;
for(;i<=p;i++){
curr.remove(chars[i]);
}
}
}
return longest;
}
}