首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java字符数组打印索引

Java字符数组打印索引
EN

Stack Overflow用户
提问于 2016-09-16 14:00:29
回答 5查看 1.2K关注 0票数 4

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“

到目前为止,我尝试的是

代码语言:javascript
复制
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

有人能帮我解释一下这个逻辑吗?

EN

Stack Overflow用户

发布于 2016-09-16 14:54:02

这只适用于第二个示例,因为字符是按顺序出现的。

但是,您需要根据以前是否搜索过该字符的字符串(在找到字符后开始搜索)来决定开始搜索的索引。

例如。

代码语言:javascript
复制
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存储索引,并使用下面的代码高效地检索索引:

代码语言:javascript
复制
// 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());
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39524638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档