计算每个唯一字符的出现次数 [英] Count occurrences of each unique character

查看:99
本文介绍了计算每个唯一字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查找字符串中每个唯一字符的出现次数?您最多可以使用一个循环。请发布您的解决方案,谢谢。

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.

推荐答案

由于这听起来像是一个家庭作业问题,让我们试着回顾一下如何解决这个问题用手。一旦我们这样做,让我们看看我们如何尝试在代码中实现它。

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.

需要做什么?

让我们采取以下字符串:

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. 迭代字符串的每个字符

  2. 记住每个字符的次数字符串出现

我们如何实际尝试?

手动执行此操作可能是这样的:

Doing this this by hand might be like this:

首先,我们找到一个新的characeter i ,所以我们可以注意到在一张桌子中并说到目前为止出现了一次:

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

其次,我们发现另一个新字符 t ,所以我们可以在上表中添加:

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

第四,我们遇到 i 哪个恰好存在于表中。因此,我们希望检索现有的计数,并将其替换为现有的计数+ 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

等等。

如何翻译成代码?

将上述内容翻译成代码,我们可能会这样写:

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


  • 对于字符串中的每个字符

    • 检查字符是否已被遇到

      • 如果不是,那么请记住新角色并说我们遇到过一次

      • 如果是,则取其遇到的次数,并将其递增一次

      用于实施,正如其他人所提到的,使用循环和 Map 可以实现所需。

      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.

      地图 (例如 HashMap )可用于跟踪角色拥有应用的次数耳。在这种情况下,将是字符,将是字符出现次数的计数。

      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.

      祝你好运!

      这篇关于计算每个唯一字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆