Given a string, we need to check whether it has duplicate letters in it. The output should be true
if the string has duplicates, and false
otherwise.
Note: The string contains only letters.
str="educative"
true
As there are duplicate letters in the string, the output is true
.
str="answer"
false
As there are no duplicate letters in the string, the output is false
.
The solution is to use a set data structure that maintains the already seen letters.
The steps of the algorithm are as follows:
true
and exit.false
now.import java.util.HashSet;import java.util.Set;class Main{public static boolean duplicateExists(String text){Set<Character> characters = new HashSet<>();for(char ch: text.toCharArray()){if(characters.contains(ch)) return true;characters.add(ch);}return false;}public static void main(String[] args) {String text = "educative";System.out.println(duplicateExists(text));}}
Set
and HashSet
.duplicateExists()
that takes a string and checks for duplicate characters or letters.text
.duplicateExists()
method with text
as the string.