Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

java - Count occurrences of each unique character

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...