Write a java program to count Unique Characters in String.
Given a String as input, write a program to count and print the number of unique characters in it.
If there are no unique characters in the string, the method returns -1
Input and Output Format:
Input consists of a string.
The output consists of an integer.
Sample Input 1:
HOWAREYOU
Sample Output 1:
7
(Hint: Unique characters are: H, W, A, R, E, Y, U and other characters are repeating)
Sample Input 2:
MAMA
Sample Output2:
-1
Count Unique Characters in String in Java.
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); getvalues(s1); } public static void getvalues(String s1) { String s2 = s1.toLowerCase(); StringBuffer sb = new StringBuffer(s2); int l = sb.length(); int count = 0; for (int i = 0; i < l; i++) { count = 0; for (int j = i + 1; j < l; j++) { if (sb.charAt(i) == sb.charAt(j)) { sb.deleteCharAt(j); count++; j--; l--; } } if (count > 0) { sb.deleteCharAt(i); i--; l--; } } if (sb.length() == 0) { System.out.println(-1); } else System.out.println(sb.length()); } }