char_array[]是"x,a,x,c,x,b,x,a,x,x,b,x,x“
key_array[]是"a,b,c“
预期返回数组:"1,5,3“
目标是打印与key_array匹配的char_array的索引。例如,在这种情况下,程序必须打印"1,5,3“。它只计算它匹配的第一个索引。
另一个例子是
char_array[]是"q,h,e,h,w,e,r,t,l,y,l,l,o“
key_array[]是"h,e,l,l,o“
预期返回数组:"1,2,8,10,12“
到目前为止,我尝试的是
int index = 0;
for(int i = 0; i < key_array.length; i++)
{
isFound = false;
for(int k = index + 1; k < char_array.length && isFound == false; k++)
{
if(char_array[i] == key_array[k])
{
index = k;
num[j] = index;
isFound = true;
}
}
}这样,我的第二个处理"hello“的示例可以工作,但我的第一个处理"abc”的示例不能工作。
我的k是从index+1开始的,但我想我必须将它从0改为char_array.length。
有人能帮我解释一下这个逻辑吗?
发布于 2016-09-16 14:54:02
这只适用于第二个示例,因为字符是按顺序出现的。
但是,您需要根据以前是否搜索过该字符的字符串(在找到字符后开始搜索)来决定开始搜索的索引。
例如。
for (int i = 0; i < key_array.length; i++) {
char c = key_array[i];
int previousIndex;
// go back and find the last index with a matching char
for (previousIndex = i-1; previousIndex >= 0 && key_array[previousIndex] != c; previousIndex--) {}
if (previousIndex >= 0 && num[previousIndex] == -1) {
// last key not found => no further matches available
num[i] = -1;
} else {
// find occurence of char after last match
num[i] = -1;
for (int j = (previousIndex >= 0 ? num[previousIndex] + 1 : 0); j < char_array.length; j++) {
if (char_array[j] == c) {
num[i] = j;
break;
}
}
}
}或者,使用Map通过char存储索引,并使用下面的代码高效地检索索引:
// find list of indices by char
Map<Character, ?> map = IntStream.range(0, char_array.length).boxed().collect(Collectors.groupingBy(i -> char_array[i]));
for (Map.Entry e : map.entrySet()) {
// replace values with iterator over index lists
e.setValue(((List)e.getValue()).iterator());
}
for (int i = 0; i < key_array.length; i++) {
Iterator<Integer> iterator = (Iterator<Integer>) map.get(key_array[i]);
num[i] = (iterator == null || !iterator.hasNext() ? -1 : iterator.next());
}https://stackoverflow.com/questions/39524638
复制相似问题