Java字符数组打印索引

4

char_array[]是"x,a,x,c,x,b,x,a,x,x,b,x,x,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”却不能工作。

我开始使用index + 1来定义我的k,但我想我需要把它从0改为char_array.length

请有经验的人帮我看看这个逻辑。


提示:循环遍历“key”数组,对于每个字符C,循环遍历另一个数组,并在找到C时打印索引和break,然后重复此过程。 - user180100
2
为什么“h,e,l,l,o”版本不会输出“1,2,8,8,12”? - Tibrogargan
1
你需要注意重新将“index”初始化为0。 - Thiyagu
@user7 但是当我重新将索引初始化为0时,它会再次计算索引,就像上面的hello示例一样,它不应该打印1 2 8 8 12,而应该是1 2 8 10 12。 - Eric
@Eric,顺便说一下,你的代码片段是错误的,应该是char_array[k] == key_array[i] - somebody
显示剩余4条评论
5个回答

2
尝试这个;
for(int i=0;i<key_array.length;i++)
{
    int pos=new String(char_array).indexOf(key_array[i]);

    char_array[pos]='0'                          //considering there is no numeric character in char_array  

    collection.push(pos);                        //collection is a java Collection framework's object
}

为什么不呢?char_array从未被更新。在循环内部重新创建字符串是毫无意义的。 - OneCricketeer
1
@cricket_007 可以使用 indexOf。有点棘手。太糟糕了,输出结果是错误的,这本来是一个不错的解决方案。 - Tibrogargan
此外,这并没有考虑到重复的字符不能有相同的数字。请参考“hello”示例。 - OneCricketeer
我以为你要求将整个语句放在循环外面。 - KOUSIK MANDAL
@Tibrogargan - 字符串应该移动到循环外的变量中。indexOf 应该保留。 - OneCricketeer
2
将字符串的创建移出循环只是编译器本来就会进行的优化。真正的问题在于该解决方案产生了错误的结果。 - Tibrogargan

0

看起来能解决问题

static int[] foo(char[] char_array, char[] key_array) {
    // copy the original so we can modify to avoid repeats
    char[] copy = new char[char_array.length];
    System.arraycopy(char_array, 0, copy, 0, char_array.length);
    int[] result = new int[key_array.length];
    boolean found = true;
    for(int i = 0; found && i < key_array.length; i++) {
        found = false;
        for(int j = 0; j < copy.length; j++) {
            if (copy[j] == key_array[i]) {
                copy[j] = 0;
                result[i] = j;
                found = true;
                break;
            }
        }
    }
    if (found) {
        return result;
    }
    return null;
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(foo("xaxcxbxaxxbxxxx".toCharArray(), "abc".toCharArray())));
    System.out.println(Arrays.toString(foo("qhehwertlyllo".toCharArray(), "hello".toCharArray())));
}

0

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

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

例如:

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());
}

0

我认为这个可以胜任(O(n)):

char[] char_array = {'q', 'h', 'e', 'h', 'w', 'e', 'r', 't', 'l', 'y', 'l', 'l', 'o'};
char[] key_array = {'h', 'e', 'l', 'l', 'o'};

Map<Character, Queue<Integer>> charPossitions = new HashMap<Character, Queue<Integer>>();
for(int i = 0; i < char_array.length; i++){
    if(charPossitions.get(char_array[i]) == null){           
       Queue<Integer> possitionsQueue=new LinkedList<Integer>();
       possitionsQueue.add(i);
       charPossitions.put(char_array[i], possitionsQueue);
    }else { 
       charPossitions.get(char_array[i]).add(i);
    }                                           
}
for(char key : key_array){
    System.out.println(key + "/" + charPossitions.get(key).poll());
}

0

你好,这应该可以解决问题!

public class Main
{

  private static final char[] liste1 = {'x', 'a', 'x', 'c', 'x', 'b', 'x', 'a', 'x', 'x' ,'b' ,'x' ,'x', 'x', 'x'};
  private static final char[] liste2 = {'q', 'h', 'e', 'h', 'w', 'e', 'r', 't', 'l', 'y', 'l', 'l', 'o'};
  private static final char[] key1 = {'a', 'b', 'c'};
  private static final char[] key2 = {'h', 'e', 'l', 'l', 'o'};


  private static void lookupIndexOfChar(char c, char[] list, List<Integer> result){
    for(int i = 0; i < list.length; i++){
      if(list[i] == c){
        if(notInResult(i, result)){
          result.add(i);
          break;
        }
      }
    }
  }

  private static boolean notInResult(int i, List<Integer> result)
  {
    return !(result == null || result.contains(i));
  }

  public static void main(String[] args){
    List<Integer> result = new ArrayList<Integer>();
    for (char c : key1)
    {
      lookupIndexOfChar(c, liste1, result);
    }
    for (Integer integer : result)
    {
      System.out.print(integer);
    }
    System.out.println(" ");
    result.clear();
    for (char c : key2)
    {
      lookupIndexOfChar(c, liste2, result);
    }
    for (Integer integer : result)
    {
      System.out.print(integer);
    }
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接