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

234
Views
Salida duplicada en Java

Soy nuevo aquí y sigo aprendiendo. Hoy aprendo a encontrar duplicados en cadenas. Desde https://www.javatpoint.com/program-to-find-the-duplicate-characters-in-a-string , trato de aprender el código completo de la web.

Cuando cadena = "Gran responsabilidad", la salida será:

 Duplicate characters in a given string: r e t s i

porque tiene el caracter duplicado retsi

Y cuando la cadena es "genial", la salida es

 Duplicate characters in a given string:

El resultado está en blanco porque no hay caracteres duplicados, así que doy una descripción "sin duplicado" para definir ningún carácter duplicado y el resultado es así

 Duplicate characters in a given string: no duplicates no duplicates no duplicates no duplicates no duplicates

Esto devuelve demasiadas descripciones.

Mi código

 public class DuplicateCharacters { public static void main(String[] args) { String string1 = "Great"; int count; //Converts given string into character array char string[] = string1.toCharArray(); System.out.println("Duplicate characters in a given string: "); //Counts each character present in the string for(int i = 0; i <string.length; i++) { count = 1; for(int j = i+1; j <string.length; j++) { if(string[i] == string[j] && string[i] != ' ') { count++; //Set string[j] to 0 to avoid printing visited character string[j] = '0'; } } //A character is considered as duplicate if count is greater than 1 if(count > 1 && string[i] != '0') System.out.println(string[i]); else System.out.println("no duplicates"); } } }

¿Cómo puedo imprimir solo una descripción sin repetición? Intenté devolver 0; Pero no funciona.

Rendimiento esperado

 Duplicate characters in a given string: no duplicates
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Separe la lógica para encontrar duplicados de cómo informa los hallazgos al usuario. Mueva la lógica para encontrar los duplicados en un método. Pase los resultados de esa salida a otro método. El método principal invoca el primero y pasa la salida al segundo.

 public static void main(String[] args) { String s = .... whatever you are searching for duplicates in .... reportDuplicates(findDuplicates(s)): } public static List<Character> findDuplicates(String s) { ... returns a List containing duplicates ... } public static void reportDuplicates(List<Character> duplicates) { if (null == duplicates || duplicates.isEmpty()) { ... report no duplicates ... } else { ... output the duplicates } }
over 4 years ago · Santiago Trujillo Report

0

Agregue una bandera a su programa que indique si hay duplicados o no. Y después del ciclo, verifique si esta bandera es true o false .

Este método se vería a continuación. Comenté el código donde lo actualicé.

 public static void main(String[] args) { String string1 = "Great"; int count; //Converts given string into character array char string[] = string1.toCharArray(); // here is flag added boolean noDuplicates = true; System.out.println("Duplicate characters in a given string: "); //Counts each character present in the string for(int i = 0; i <string.length; i++) { count = 1; for(int j = i+1; j <string.length; j++) { if(string[i] == string[j] && string[i] != ' ') { count++; //Set string[j] to 0 to avoid printing visited character string[j] = '0'; } } //A character is considered as duplicate if count is greater than 1 if(count > 1 && string[i] != '0') { System.out.println(string[i]); //here is flag updated if duplicates are found noDuplicates = false; } } //here is flag check if (noDuplicates) { System.out.println("no duplicates"); } }

Y por cierto. Su algoritmo tiene una complejidad de tiempo O (n ^ 2). Puedes encontrar uno que sea mejor ;-)

over 4 years ago · Santiago Trujillo Report

0

Es normal su System.out.println("sin duplicados"); está en su ciclo, por lo que cada vez que un carácter no está duplicado, imprime "sin duplicados".

Puede definir un booleano que se volverá verdadero si se encuentra un duplicado, como este:

 public class DuplicateCharacters { public static void main(String[] args) { String string1 = "Great"; int count; //Converts given string into character array char string[] = string1.toCharArray(); System.out.println("Duplicate characters in a given string: "); //Counts each character present in the string Boolean dupCarac = false; for(int i = 0; i <string.length; i++) { count = 1; for(int j = i+1; j <string.length; j++) { if(string[i] == string[j] && string[i] != ' ') { count++; //Set string[j] to 0 to avoid printing visited character string[j] = '0'; } } //A character is considered as duplicate if count is greater than 1 if(count > 1 && string[i] != '0'){ System.out.println(string[i]); dupCarac = true; } } if (!dupCarac){ System.out.println("no duplicates"); } }

PD: Pon {} en tu if y else.

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!