Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
Find word duplicate in string without using Hashmap, HashSet etc. in Java

I have the below code which does find duplicates in a String without HashMap, HashSet etc. but I want a better solution than this one. Please help I am new to Java programming. I believe Java is powerful enough to give that P.S- Its not that i am trying to avoid HashMap et al in Java Collections. I just want a sleeker solution

public class practice {
    static void countWords(String st){
         //split text to array of words
         String[] words=st.split("\\s");
       //frequency array
         int[] fr=new int[words.length];
       //init frequency array
         for(int i=0;i<fr.length;i++)
           fr[i]=0;
         //count words frequency
         for(int i=0;i<words.length;i++){
           for(int j=0;j<words.length;j++){
             if(words[i].equals(words[j])) 
               {
                 fr[i]++;

                    }
                }
               }

         //clean duplicates
           for(int i=0;i<words.length;i++){
             for(int j=0;j<words.length;j++){
               if(words[i].equals(words[j])) 
               {
                 if(i!=j) words[i]="";

               }
         }
         }

    //show the output

    int total=0;
    System.out.println("Duplicate words:");
    for(int i=0;i<words.length;i++){

    if(words[i]!=""){


    System.out.println(words[i]+"="+fr[i]);

    total+=fr[i];

    }    
       }

    System.out.println("Total words counted: "+total);
     }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
           countWords("apple banna apple fruit sam fruit apple hello hi hi hello hi");  
    }

}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Though Hashmap and Hashset best suit this requirement. But in case you don't want to use it you can also achieve the same thing more efficiently:

  1. Split the sentence into array and then sort it alphabetically (first letter) using Array.sort();. Once sorted you can iterate through the array and store the repeated count of words in linear time.
  2. Use tries data structure.
over 4 years ago · Santiago Trujillo Relatório

0

You can use Java8 streams to write your entire countWords method in a single line code (follow the inline comments):

static void countWords(String st){
  Map<String, Long> wordsAndCounts = 
     Arrays.stream(st.split("\\s")).    //Splt the string by space i.e., word
         collect(Collectors.groupingBy( //Apply groupby
         Function.identity(),          //Map each word
         Collectors.counting()         //Count how many words
     ));
    System.out.println(wordsAndCounts);
}

OUTPUT:

{banna=1, hi=3, apple=3, fruit=2, hello=2, sam=1}
over 4 years ago · Santiago Trujillo Relatório

0

public static void main(String[] args) {
        String s = "abcabcc abc abcdeffrgh";
        char[] ch = s.toCharArray();
        String temp = "";
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            int count = 0;
            char result = 0;
            for (j = 0; j < s.length(); j++) {
                if (ch[i] == ch[j]) {
                    result = ch[i];
                    count = count + 1;
                } else {
                    result = ch[i];
                }
            }
            if (!temp.contains(Character.toString(ch[i]))) {
                temp = temp + ch[i];
                System.out.println(result + "--count--" + count);
            }

        }
    }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda