DistinctCharacters(str) determine if it contain 10 distinct characters Java write code
- User
DistinctCharacters(str) determine if it contain 10 distinct characters Java write code
- Assistant
You can use a HashSet to check if a string contains 10 distinct characters. Here's an example code:
import java.util.HashSet; public class Main { public static void main(String[] args) { String str = "abcde12345"; // change this string to test different inputs boolean has10DistinctChars = DistinctCharacters(str); System.out.println(has10DistinctChars); } public static boolean DistinctCharacters(String str) { HashSet<Character> charSet = new HashSet<>(); for (int i = 0; i < str.length(); i++) { charSet.add(str.charAt(i)); if (charSet.size() > 10) { return false; // return false if more than 10 distinct characters are found } } return charSet.size() == 10; // return true if exactly 10 distinct characters are found } }