How can I count and print duplicate strings in a string array in Java?

java

11059 просмотра

7 ответа

194 Репутация автора

I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task.

I have one array

String [] array = {anps, anps, anps, bbo, ehllo};

I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone

The output needs to be like this

anps anps anps
bbo
ehllo

I have tried while, for loops but the logic seems impossible.

Автор: thecodefather Источник Размещён: 14.06.2012 07:53

Ответы (7)


1 плюс

6922 Репутация автора

If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print() if they are not equal do a System.Out.println().

String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary. 
Arrays.sort(array);
for(int i = 0; i < array.length; i++){
    if((i+1)==array.length || !array[i].equals(array[(i+1)])){
        System.out.println(array[i]);
    } else {
        System.out.print(array[i]+" ");
    }
}
Автор: NominSim Размещён: 14.06.2012 07:56

2 плюса

16271 Репутация автора

There are multiple ways of achieving this.

  1. Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
  2. You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array

The second way is better. The code is something like:

Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
       int nOcc = 1;
       if(occurences.containsKey(array[index]){
         nOcc = occurences.get(array[index]) + 1;
       }
       occurences.remove(array[index]);
       occurences.put(array[index], nOcc);
}

At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)

Автор: GETah Размещён: 14.06.2012 07:57

0 плюса

4573 Репутация автора

Complexity n^2 , just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.

Complexity nlogn + n == nlogn , merge or quick sort, and after this go to the end and pring sequenced values. There are more solutions but I think its enough for you.

Автор: Sergii Zagriichuk Размещён: 14.06.2012 07:59

2 плюса

745 Репутация автора

Решение

Sort the array first then

for(int i = 0, i < array.length; i++){
    String temp = array[i];
    System.out.print(temp+" ");
    for(int j = i+1; j < array.length; j++){
        String temp2 = array[j];
        if(temp.compareTo(temp2) == 0){
            System.out.print(temp2+" ");
            i++;
        }
    }
    System.out.println();
}

or something similar...

Автор: javajavajava Размещён: 14.06.2012 08:02

0 плюса

628 Репутация автора

Naive Algorithms

  • Create a Map
  • Iterate through all array
  • check if key already exist in map
  • if yes update value +1
  • if no insert
  • print the map as you want

You should be able to do what you're looking for !

Автор: Jean-Christophe Fortin Размещён: 14.06.2012 08:03

9 плюса

3984 Репутация автора

Okay, there are a worryingly number of either wrong answers or answers that use HashMap or HashSet for this very simple iteration problem, so here is a correct solution.

Arrays.sort(array);

for (int i = 0; i < array.length; ++i){
    if (i+1 == array.length) {
        System.out.println(array[i]);
    } else if (array[i].equals(array[i+1])) {
        System.out.print(array[i]+" ");
    } else {
        System.out.println(array[i]);
    }
}
Автор: Hans Z Размещён: 14.06.2012 08:11

0 плюса

1 Репутация автора

Use below logic

import java.util.ArrayList;


public class RepeatStringPrint {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
            String total[] = new String[50];
            String sTotal[] = null;
            for (int i = 0; i < x.length; i++) {
                total[i] = x[i];
            }
            for (int k = 0; k < total.length; k++) {
                int count = 0;
                if (total[k] != null) {
                    sTotal = new String[50];
                    for (int i = 0; i < total.length; i++) {
                        if (total[k] == total[i]) {
                            count++;
                            if (count <= 1) {
                                sTotal[i] = total[k];
                            }
                        }
                    }
                    if (sTotal[k] != null) {
                        for(int j=0; j<count; j++){
                            System.out.print(sTotal[k]+"\t");
                        }
                        System.out.print("\n");
                    }
                }

            }
        }
        catch (Exception e) {

        }
    }

}
Автор: Anil Patile Размещён: 12.07.2014 05:19
Вопросы из категории :
32x32