【题目】:求一个字符串中不重复字符的最长子串,如字符串“abacdefgafg”,最长的不重复的子串为“acdefg”,长度为6,当有两个长度相同的字符串,输出第一个最长的字符子串。
基本算法+Hash
最直接的方法就是遍历每个字符起始的子串,辅助hash,寻求最长的不重复子串,时间复杂度为O(n^2),n为字符串的长度。
public String getLNRS(String str) {
if (str == null)
return str;
int maxLen = 0;
int index = 0;
int j = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<str.length(); i++) {
map.clear();
map.put(str.charAt(i), 1);
for (j=i+1; j<str.length(); j++) {
if (map.get(str.charAt(j)) != null) {
break;
}
map.put(str.charAt(j), 1);
}
if (j-i > maxLen) {
maxLen = j-i;
index = i;
}
}
return str.substring(index, index+maxLen);
}
DP方案
对于最长不重复子串,某个当前的字符,如果它与前面的最长不重复子串中的字符没有重复,那么就可以以它为结尾构成新的最长子串;如果有重复,且重复位置在上一个最长子串起始位置之后,那么就与该起始位置之后的稍短的子串构成新的子串或者单独成一个新子串。
我们首先使用O(n^2)的DP方案:在内层循环遍历到上一个最长子串的起始位置。
public String getLNRS(String str) {
if (str == null)
return str;
int maxLen = 0;
int index = 0;
int lastIndex = 0;
int[] dp = new int[str.length()];
dp[0] = 1;
for (int i=1; i<str.length(); i++) {
for (int j=i-1; j>=lastIndex; j--) {
if (str.charAt(i) == str.charAt(j)) {
dp[i] = i-j;
lastIndex = j+1;
break;
} else if (j == lastIndex){
dp[i] = dp[i-1] + 1;
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
index = i+1-maxLen;
}
}
return str.substring(index, index+maxLen);
}
DP+Hash
上面的DP方法依然是O(n^2),因为每次我们都需要“回头”去寻找重复元素的位置。我们知道可以用hash记录元素是否出现过,这样就不必“回头”了,而时间复杂度必然降为O(N),只不过需要额外的空间消耗。
public String getLNRS(String str) {
if (str == null)
return str;
int maxLen = 0;
int index = 0;
int lastIndex = 0;
int[] dp = new int[str.length()];
dp[0] = 1;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put(str.charAt(0), 0);
for (int i=1; i<str.length(); i++) {
if (map.get(str.charAt(i)) == null) {
map.put(str.charAt(i), i);
dp[i] = dp[i-1] + 1;
} else {
if (lastIndex <= map.get(str.charAt(i))) {
dp[i] = i-map.get(str.charAt(i));
lastIndex = map.get(str.charAt(i))+1;
map.remove(str.charAt(i));
map.put(str.charAt(i), i);
} else {
dp[i] = dp[i-1]+1;
map.remove(str.charAt(i));
map.put(str.charAt(i), i);
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
index = i+1-maxLen;
}
}
return str.substring(index, index+maxLen);
}
进一步优化
写到现在,发现辅助空间用的比较多,对于DP方程:
dp[i] = dp[i-1] + 1;
我们不需要O(n)的辅助空间去存储子问题的最优解,只需要O(1)的空间存储上一次的最优解即可,然后每次循环之后更新。
public String getLNRS(String str) {
if (str == null)
return str;
int maxLen = 0;
int index = 0;
int lastIndex = 0;
int current = 1;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put(str.charAt(0), 0);
for (int i=1; i<str.length(); i++) {
if (map.get(str.charAt(i)) == null) {
map.put(str.charAt(i), i);
current++;
} else {
if (lastIndex <= map.get(str.charAt(i))) {
current = i-map.get(str.charAt(i));
lastIndex = map.get(str.charAt(i))+1;
map.remove(str.charAt(i));
map.put(str.charAt(i), i);
} else {
current++;
map.remove(str.charAt(i));
map.put(str.charAt(i), i);
}
}
if (current > maxLen) {
maxLen = current;
index = i+1-maxLen;
}
}
return str.substring(index, index+maxLen);
}
http://xfhnever.com/2014/10/30/algorithm-lnrs/