2

How to find the number of occurrence of every unique character in a String? You can use at most one loop. please post your solution, thanks.

didxga
  • 5,935
  • 4
  • 43
  • 58
  • 3
    Homework? Show us what you've done. – wkl Nov 06 '10 at 05:52
  • 2
    How to find what you've done already ? You can try to solve yourself first and then ask questions about problems you having. please post what you've done, thanks. – Bert F Nov 06 '10 at 06:00
  • @Bert F my solution is similar to @zengr's, i was wondering if there is a better way, so i post the question here. – didxga Nov 06 '10 at 06:36

3 Answers3

12

Since this sounds like a homework problem, let's try to go over how to solve this problem by hand. Once we do that, let's see how we can try to implement that in code.

What needs to be done?

Let's take the following string:

it is nice and sunny today.

In order to get a count of how many times each character appears in the above string, we should:

  1. Iterate over each character of the string
  2. Keep a tally of how many times each character in the string appears

How would we actually try it?

Doing this this by hand might be like this:

First, we find a new characeter i, so we could note that in a table and say that i appeared 1 time so far:

'i'  ->  1

Second, we find another new character t, so we could add that in the above table:

'i'  ->  1
't'  ->  1

Third, a space, and repeat again...

'i'  ->  1
't'  ->  1
' '  ->  1

Fourth, we encounter an i which happens to exist in the table already. So, we'll want to retrieve the existing count, and replace it with the existing count + 1:

'i'  ->  2
't'  ->  1
' '  ->  1

And so on.

How to translate into code?

Translating the above to code, we may write something like this:

  • For every character in the string
    • Check to see if the character has already been encountered
      • If no, then remember the new character and say we encountered it once
      • If yes, then take the number of times it has been encountered, and increment it by one

For the implementation, as others have mentioned, using a loop and a Map could achieve what is needed.

The loop (such as a for or while loop) could be used to iterate over the characters in the string.

The Map (such as a HashMap) could be used to keep track of how many times a character has appeared. In this case, the key would be the character and the value would be the count for how many times the character appears.

Good luck!

coobird
  • 159,216
  • 35
  • 211
  • 226
5

It's a homework, so cannot post the code, but here is one approach:

  1. Iterate through the string, char by char.
  2. Put the char in a hashmap key and initialize its value to 1 (count). Now, if the char is encountered again, update the value (count+1). Else add the new char to key and again set its value (count=1)
zengr
  • 38,346
  • 37
  • 130
  • 192
  • 1
    Thanks :-), it's actually a interview question i answered few days ago, and your answer is similar to mine. i post the question here cause i want to know what is other programmer's thought on this. – didxga Nov 06 '10 at 06:26
  • I guess hashmap is the best possible answer to this problem. – zengr Nov 06 '10 at 06:28
0
Here you go! I have done a rough program on Count occurrences of each unique character

public class CountUniqueChars{
    public static void main(String args[]){
        HashMap<Character, Integer> map;        
        ArrayList<HashMap<Character, Integer>> list = new ArrayList<HashMap<Character,Integer>>();
        int i;
        int x = 0;
        Boolean fire = false;

        String str = "Hello world";
        str = str.replaceAll("\\s", "").toLowerCase();
        System.out.println(str.length());

        for(i=0; i<str.length() ; i++){
            if(list.size() <= 0){
                map = new HashMap<Character, Integer>();
                map.put(str.charAt(i), 1);
                list.add(map);
            }else{              
                map = new HashMap<Character, Integer>();
                map.put(str.charAt(i), 1);

                fire = false;

                for (HashMap<Character, Integer> t : list){
                    if(t.containsKey(str.charAt(i)) == map.containsKey(str.charAt(i))){                 
                        x = list.indexOf(t);
                        fire = true;

                        map.put(str.charAt(i), t.get(str.charAt(i))+1);
                    }
                }               

                if(fire){
                    list.remove(x);
                }   

                list.add(map);

            }           
        }
        System.out.println(list);       
    }
}
ram_c
  • 87
  • 2
  • 11