Find first duplicate or repeated character in a string - JAVA

No comments
In this tutorial we will write the algo with program in java to find the first duplicate character in a string.
Problem- Suppose we have a string 'tutorialsinn' and we want to find the first duplicate or repeated character in this string.
Solution-
  • First convert the string to character array using java String method toCharArray().
  • Loop through the array and put each element in HashSet, if it doesn't exists already.
  • If characther already exists inside the HashSet that means the character is duplicate, so return that character.
Now we will write a simple code in java to implement the steps described above.

package com.tutorialsinn.algos;

import java.util.HashSet;

public class SearchFirstChar {

public static char firstDuplicate(String s){
  char [] arr = s.toCharArray();
  HashSet<Character> set = new HashSet<>();
  
  
for(char c: arr){
   if(set.contains(c)){
    return c;
   }
   
   set.add(c);
  }
  return  '\0'; 
 }

}

 public static void main(String args[]) {
  // string to be checked
  String str = "tutorialsinn";
  
  System.out.println(firstDuplicate(str) == '\0' ? "No duplicate char found" : firstDuplicate(str));
  
  }

If you have any doubt or got some queries, please don't forget to write it in comments below.

No comments :

Post a Comment