In this post well see a Java program to find the first repeated character in a String. This program is reverse of another Java program where you are asked to find the first non-repeated character in a String.
As example if given string is “Java” then first repeated character is ‘a'.
If given String is “net” then there is no repeated character.
Solution for finding the first repeated character in a String
There are many ways to write this program, option you chose also depends upon whether you can use any existing API or not.
- First solution is to use outer and inner loop and traverse String starting from first character if that character is found again return that character otherwise move to the next character. This is a O(n2) solution.
- If you are permitted to use any existing API then you can use HashSet to add elements of the array. Since HashSet stores only unique elements so false is returned for the repeated character. This solution needs extra space as apart from array a HashSet is also used.
Find first repeated character in a String using loops
In this solution outer and inner for loops are used and String is searched character by character to find repeated char.
public class FirstRepeated { public static void main(String[] args) { String str = "Java programming"; int index = findFirstRepeated(str); if(index != -1){ System.out.println("First Repeated character " + str.charAt(index) + " found at index " + index); }else{ System.out.println("No repeated character found"); } } private static int findFirstRepeated(String str){ for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); for(int j = i+1; j < str.length(); j++){ if(c == str.charAt(j)) return j; } } return -1; } }
Output
First Repeated character a found at index 3
Find first repeated character in a String using HashSet
In this solution for finding the first repeated character in a String each character of the String is added to the HashSet. In HashSet if duplicate element is added it returns false which gives us the repeated character in the String.
public class FirstRepeated { public static void main(String[] args) { String str = "hashset"; int index = findFirstRepeated(str); if(index != -1){ System.out.println("First Repeated character " + str.charAt(index) + " found at index " + index); }else{ System.out.println("No repeated character found"); } } private static int findFirstRepeated(String str){ Set<Character> charSet = new HashSet<>(); for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); if(!charSet.add(c)){ return i; } } return -1; } }
Output
First Repeated character h found at index 3
That's all for this topic Find The First Repeated Character in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment