Write a java program to find unique characters in a string.

Write a program that takes a string and returns the number of unique characters in the string. If the given string does not contain any unique characters return -1.

The return type of the output is the count of all unique characters in the strings.

Input and Output Format:

Input consists a string.

The output is an integer.

Refer sample output for formatting specifications.

Sample Input 1:

HelloWorld

Sample Output 1:

5

Sample Input 2:

coco

Sample Output 2:

-1

Find unique characters in a string in Java.

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) throws ParseException {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    StringBuffer sb = new StringBuffer(s1);
    for (int i = 0; i < sb.length(); i++) {
      int count = 0;
      for (int j = i + 1; j < sb.length(); j++) {
        if (sb.charAt(i) == sb.charAt(j)) {
          sb.deleteCharAt(j);
          j--;
          count++;
        }
      }
      if (count >= 1) {
        sb.deleteCharAt(i);
        i--;
      }
    }
    System.out.println(sb.length());
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

17 − 5 =