How to check if string contain duplicate letters in Java

1 Answer

0 votes
import java.util.HashSet;
import java.util.Set;

public class MyClass {
    public static boolean duplicateLettersExists(String str) {
        Set<Character> char_set = new HashSet<>();
        
        for (char ch: str.toCharArray()) {
            if (char_set.contains(ch)) return true;
                char_set.add(ch);
        }
        return false;
    }
    public static void main(String args[]) {
        String str = "java csharp c c++";
        
        System.out.println(duplicateLettersExists(str));
    }
}




/*
run:

true

*/

 



answered Jul 17, 2022 by avibootz
edited Jul 17, 2022 by avibootz

Related questions

1 answer 152 views
3 answers 235 views
1 answer 192 views
1 answer 154 views
1 answer 147 views
1 answer 204 views
...