Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
Encuentre palabra duplicada en cadena sin usar Hashmap, HashSet, etc. en Java

Tengo el siguiente código que encuentra duplicados en una Cadena sin HashMap, HashSet, etc. pero quiero una mejor solución que esta. Por favor ayuda, soy nuevo en la programación de Java. Creo que Java es lo suficientemente poderoso como para dar ese PS: no es que esté tratando de evitar HashMap et al en Java Collections. Solo quiero una solución más elegante

 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 answers
Answer question

0

Aunque Hashmap y Hashset se adaptan mejor a este requisito. Pero en caso de que no quiera usarlo, también puede lograr lo mismo de manera más eficiente:

  1. Divida la oración en una matriz y luego ordénela alfabéticamente (primera letra) usando Array.sort();. Una vez ordenado, puede iterar a través de la matriz y almacenar el recuento repetido de palabras en tiempo lineal.
  2. Utilice la estructura de datos de intentos .
over 4 years ago · Santiago Trujillo Report

0

Puede usar secuencias Java8 para escribir todo su método countWords en un código de una sola línea (siga los comentarios en línea):

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

PRODUCCIÓN:

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!