问题描述:
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.
import java.util.HashSet;
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<String,String> hs = new HashMap<String,String>();
int length = 0;
int memoLength = 0;
for(int i=0;i<s.length();i++){
hs.clear();
length = 0;
if(memoLength>s.length()-i&&memoLength!=0){
break;
}
for(int j=i;j<s.length();j++){
/*
* 记录memoLength,两种情况
*/
if(!hs.containsKey(s.substring(j, j+1))){
length++;
hs.put(s.substring(j, j+1),s.substring(j,j+1));
if(memoLength<length){
memoLength = length;
}
}else{
if(length>memoLength){
memoLength=length;
}
break;
}
}
}
return memoLength;
}
}
上午看了看动态规划,准备用动归来求解这个问题,后来看了一下tag觉得自己想太多。
该题使用散列表,但是速度不尽人意,之后在看一下大牛的实现。
另:如果不使用hashset使用hashmap会tle。
算法可以优化的地方:在下一次的遍历过程中可以使用上一次遍历得到的最长子串的长度。