Pergunta

For example, the string "abc" should give 3 unique characters, while the string "abcccd" would give 4 unique characters. I'm not allowed to use Map, HashMap, TreeMap, Set, HashSet, StringBuffer or TreeSet in this.

So far I'm trying to use a for loop but when I run the program I keep getting 0 unique characters. I'm kind of new at Java so I really have no idea what I'm doing.

Edit: so I changed the code around and I'm getting a result but it ends up being 1 less than what I want. I'll type in 'abc' and the result will come up as "2 unique characters" instead of three. To counter that I put (uniqueChars + 1) in the println statement. Is this a good correction? If the user puts nothing, it will still say that there's 1 unique character.

Updated code:

    userText = userText.toLowerCase(); // userText is declared earlier in the program 
                                       // as the user's input. Setting this to lowercase 
                                       // so it doesn't say "a" and "A" are two different 
                                       // characters.
    int uniqueChars = 0;
    for (int i = 0; i < lengthText-1; i++) { // lengthText is declared earlier 
                                              // as userText.length();
        if (userText.charAt(i) != userText.charAt(i+1))
            uniqueChars++;
    }
    System.out.println("there are " + (uniqueChars + 1) + " unique characters in your string.");
}
Foi útil?

Solução 2

This is what I came up with:

public static int countUniqueCharacters(String s) {
    String lowerCase = s.toLowerCase();
    char characters[] = lowerCase.toCharArray();
    int countOfUniqueChars = s.length();
    for (int i = 0; i < characters.length; i++) {
        if (i != lowerCase.indexOf(characters[i])) {
            countOfUniqueChars--;
        }
    }
    return countOfUniqueChars;
}

I just check the index for every character, and if it's different from the original index, there are multiple occurrences.

Outras dicas

How about this one? It's a regex solution rather than a loop:

public static int countUniqueCharacters(String input)
{
    String unique = input.replaceAll("(.)(?=.*?\\1)", "");
    return unique.length();
}

If the program needs to be case-insensitive, you can use this instead:

public static int countUniqueCharacters(String input)
{
    String unique = input.replaceAll("(?i)(.)(?=.*?\\1)", "");
    return unique.length();
}

You could make this a single-line method with return input.replaceAll(...).length();

Regex Explained:

  • . matches any character
  • (...) creates a capturing group, to be referenced later
  • (?=...) creates a lookahead, to look forwards in the input
  • .*? matches anything between the character and its match (non-greedy matching)
  • \\1 matches the first capturing group
  • (?i) sets the case-insensitive flag

So, the regex will look for any character which has a duplicate later in the string, and then replaceAll will replace it with the empty string. So, an input like "cabbacbdbadbcabdaadcb" becomes "adcb" (keeping the last of each unique character). Then, with a string containing unique characters, that string's length is the answer.

If, for some reason, you needed the unique-character string and you needed it in the original order, you would have to reverse the original string before stripping away duplicate characters (and then reverse it again when you're done). This would require either a third-party library, StringBuffer, or a loop.

You could make a new String, called uniqueChars and initialize it to "". Iterate over the characters in the String you're checking. If uniqueChars.contains(charToCheck) is false, then append that character to uniqueChars. At the end of the loop, uniqueChars.length() will tell you how many unique characters you had. It's ugly and inefficient but it should work.

use an ArrayList and add a charactar if not in there already:

list = new ArrayList<String>();
for ( /*   */ ) {  // same for loop you wrote
      String character = (String) text.charAt(i);

       if(!list.contains(character)) {  // note the '!'
            list.add(character);
       }
}

// and finally
int quantity = list.size();

Here is the program for how to write a file, how to read the same file, and how count number of times the particular character repeated:

package filereadexple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;

        /*
         * This is a program here I am creating a file by using "filewriter" 
         * and it is named as count.char and I am reading a same file and 
         * then how count number of times the particular character repeated.
         */

public class CountNoOfPartChar {

    public static void main (String args[]){

        File file = new File ("count.char");

        try{
            FileWriter fw = new FileWriter("count.char");
            fw.write("In Xanadu did Kubla Khan");
            fw.write("\r\n");
            fw.write("A stately pleasure-dome decree:");
            fw.write("\r\n");
            fw.write("Where Alph, the sacred river, ran");
            fw.write("\r\n");
            fw.write("Through caverns measureless to man");
            fw.write("\r\n");
            fw.write("Down to a sunless sea.");
            fw.close();
            FileInputStream fis = new FileInputStream(file);
            int i;
            int occurs = 0;
            char current;
            while ((i=fis.available()) > 0){
                current = (char)fis.read();
                if(current == 'a'){
                    occurs++;
                }
            }
            System.out.println("The number of particular character repeated is : " + occurs);
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

How about put it into an array, sort it alphabetically, then apply your logic(comparing adjacents)?

v  = sort(v);//your sort method

int count = 0;
for (int i = 0;i< lengthText-1; i++) 
{ if v[i] == v[i + 1]  {
        i++;
    } else {
        count++;
    }
}

By the way, your program doesn't work because you do i == lengthText-1 in your for loop.

Same logic with @Alexandre Santos, but with working sample codes. Complexity is O(N). Works only with alphabetical string without space, numeric or special characters.

This also can be used as counting sort.

public class CountChars 
{
    public static int countUniqCharacters(String str) {
        int[] counts = new int['z' - 'a' + 1];
        char[] arr = str.toLowerCase().toCharArray();

        for (char c: arr) {
            counts[c - 'a']++;
        }

        int unique = 0;
        for (int i: counts) {
            if (i > 0)
                unique++;
        }

        return unique;
    }

    public static void main(String[] args) {
        System.out.println("Unique char in " + args[0] 
                + " is " + CountChars.countUniqCharacters(args[0]));
    }
}
public class CharacterCount {
    public static void main(String[] args) {
        String s = "aaabbbcccddd";
        String t="";
        int count = 0;

        //Loop to find unique characters in a string and add it to new string called t
        //if a character is not found in a string indexOf returns -1
        for (int i = 0; i < s.length(); i++) {
            if (t.indexOf(s.charAt(i))==-1) t+=s.charAt(i);
        }

        //For every character new string t , loop though s find the count and display
        for (int i = 0; i < t.length(); i++) {
            count = 0;
            for (int j = 0; j < s.length(); j++) {
                if (t.charAt(i) == s.charAt(j)) count++;
            }
            System.out.println(t.charAt(i) + " " + count);
        }
    }
}
      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());
 }
 }

Use a vector.

    char[] letters = new char[26];
    for (char c : letters)
    {
        letters[c]=0;
    }

Then for every letter found, increment the position in the vector. If any entries have a counter greater than 1 then you have repeats

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top