将数组中的相同值合并在一起

时间:2015-05-29 06:13:57

标签: java arrays

public static String[][][] cleanUp(String[][][] array) {
    for (int f = 0; f < array.length; f++) {
        for (int g = 0; g < array[f].length; g++) {
            int position = 0;
            //boolean flag = false;
            int count = 0;
            for (int h = 0; h < array[f][g].length; h++) {
                if (array[f][g][h].equals(array[f][g][h+1])) count++;
                else {
                    ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g]));
                    for (int i = count - 1; i > position; i--) {
                        temp.remove(i);
                        position = i-1 ;
                    }
                    temp.set(position, array[f][g][h] + " (" + count + ")");
                }
            }
        }
    }
    return array;
}

基本上,我想做的是获取一个3D数组的字符串,并让每个1D数组显示重复值的数量。例如,如果我有一个像这样的字符串数组:

[go, go, go, go, go, go]
[go, stop, stop, stop]

它会变成:

[go (5)]
[go (1), stop (3)]

我怎么能这样做,我做错了什么?

1 个答案:

答案 0 :(得分:5)

你需要改变你的最后一个内循环:

        int count = 0;
        for (int h = 0; h < array[f][g].length; h++) {
            if (array[f][g][h].equals(array[f][g][h+1])) count++;
            //You dont check for out of bound here, so `h + 1` will cause out of bound error
            else {
                ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g]));
                for (int i = count - 1; i > position; i--) {
                    temp.remove(i);
                    position = i-1 ;
                }
                temp.set(position, array[f][g][h] + " (" + count + ")");
            }
            //Count is not reset after this, so this will be wrong!
        }

我该怎么做:

        ArrayList<String> tmp  = new ArrayList<>();
        for (int h = 0; h < array[f][g].length; h++) {
            int count = 1;
            while(h + count < array[f][g].length && array[f][g][h].equals(array[f][g][h+count])) 
               count++;
            tmp.add(array[f][g][h] + "(" + count + ")");
            h += count - 1;//Update h to skip identical element
        }

ArrayList tmp将保存array[f][g]的结果,您应该注意我如何相应地更新h以跳过所有相同的元素。

更新:测试result