【发布时间】:2016-04-20 18:04:00
【问题描述】:
给定一个字符串,""aabbcdeeeeggi" 和 k=3,代码应该找到最长的子字符串,最多有 k 个唯一字符。对于上面的输入,它应该是 "deeeeggi"。
Here 是 Python 中该问题的优雅 O(n) 解决方案。我正在用Java实现。但我没有得到所有输入所需的输出。
public class SubStringWithKUniqueCharacters {
public static void main(String[] args){
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 3));
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 2));
}
public static String longestSubStringWithUniqueK(String input, int k){
int len = input.length();
Set<Character> unique = new HashSet<>();
int i = 0;
int j = 0;
int count = 0;
int maxStartIndex = 0;
int maxEndIndex = 0;
int maxLen = 0;
char[] inputArr = input.toCharArray();
while (i<len){
if (count==k && j -i > maxLen){
maxStartIndex = i;
maxEndIndex = j;
maxLen = maxEndIndex - maxStartIndex;
}
if (count<k && j<len){
if (unique.add(inputArr[j])){
count++;
}
j++;
}
else {
if (unique.remove(inputArr[i])){
count--;
}
i++;
}
}
return input.substring(maxStartIndex,maxEndIndex);
}
}
这是输出:
eeeeggi //correct output
eeeggi //incorrect output
我无法捕捉到错误的位置。任何帮助将非常感激。 谢谢
【问题讨论】:
-
第一个看起来不错
k =3egi...或者它可能是deeeegg。两者都是正确的。 -
第二个应该是
eeeegg吧? -
是的,我在上面更新了
-
你可能想在循环中推进
i,只要inputArr[i]不变(顺便说一句,这只会让你更接近,你的算法不正确) -
我用相同的输入尝试了链接中的python解决方案。输出为:
bcdeeee和eeeegg。你注意到了吗? “bcdeeee”不正确。所以python的解决方案并不完美。