简体   繁体   English

查找字符串中的唯一字符及其出现次数

[英]Find unique characters in a string and the count of their occurrences

I need to count the occurrence of characters in a given string and print out the unique characters and the number of how many times they appeared.我需要计算给定字符串中字符的出现次数并打印出唯一字符以及它们出现的次数。 So, for example, if I receive a string of 'HELLO' it should print out:因此,例如,如果我收到一串“HELLO”,它应该打印出来:

H: 1, E: 1, L: 2, O: 1 H:1,E:1,L:2,O:1

This is a much-simplified version of a problem, but the answer should put me in the right direction.这是一个问题的简化版本,但答案应该让我朝着正确的方向前进。 How can I approach this problem?我该如何解决这个问题?

Thank you in advance.先感谢您。

This is more or less what it should look like in order to make it easier it prints it in JSON you can already convert it to String yourself if you want.这或多或少应该是它的样子,以便更容易以 JSON 格式打印它,如果需要,您已经可以自己将其转换为 String。

function count_occurrence(text = "") {
    const array_from_text = text.split("");
    const result = {};
    Array.from(new Set(array_from_text)).forEach(word => {
        const { length } = array_from_text.filter(w => w === word);
        result[word] = length;
    });
    return result;
};
const occurences = count_occurence("HELLO");
console.log(occurences); // {H: 1, E: 1, L: 2, O: 1}
const countChars = (str) => {
  const charCount = {} ;
  for (const c of [...str]) {
    charCount[c] = (charCount[c] || 0) + 1 ;
  }
  return charCount ;
}
console.log(countChars('HELLO')) ; // {H: 1, E: 1, L: 2, O: 1}

You could use Array.reduce() to get a count of each occurrence in the input word.您可以使用Array.reduce()来获取输入单词中每次出现的计数。

We convert the word to an array using the ... operator, then .reduce() to create an object with a property for each unique letter in the word.我们使用 ... 运算符将单词转换为数组,然后使用 .reduce() 创建一个对象,该对象具有单词中每个唯一字母的属性。

 const input = 'HELLO'; const result = [...input].reduce((acc, chr) => { acc[chr] = (acc[chr] || 0) + 1; return acc; }, {}); console.log('Result:', result)
 .as-console-wrapper { max-height: 100% !important; }

My approach to this problem is:我解决这个问题的方法是:

 let str = "HELLO"; // An object for the final result {character:count} let counts = {}; // Loop through the str... for (let index = 0; index < str.length; ++index) { // Get each char let ch = str.charAt(index); // Get the count for that char let count = counts[ch]; // If we have one, store that count plus one; if (count) { counts[ch] += 1; } else { // if not, store one counts[ch] = 1; } // or more simply with ternary operator // counts[ch] = count ? count + 1 : 1;. } console.log(counts);

Maybe the easiest answer is just split to char and put it into the map.也许最简单的答案就是拆分为 char 并将其放入地图中。

const count={}
"HELLO".split("").forEach(e=>{
count[e]??=0;
    count[e]++;
})

count is what you want. count是你想要的。

Use a dictionary like datastructure that gives you O(1) access and update times.使用像数据结构这样的字典,它可以为您提供O(1)访问和更新时间。 In JS you can use an Object literat (not recommended) or a Map .在 JS 中,您可以使用 Object literat(不推荐)或Map

Iterate over the characters of your string and update the dictionary by incrementing the character count of the current character.遍历字符串的字符并通过增加当前字符的字符数来更新字典。 If it isn't in your dictionary add it and set the count to one.如果它不在您的字典中,请将其添加并将计数设置为 1。

When done with the iteration, iterate over the keys of your dictionary, where the values are the the number of occurence of that specific character, and output them in any format of your liking.完成迭代后,迭代字典的键,其中值是该特定字符的出现次数,并以您喜欢的任何格式输出它们。

 const myStr = "Hello" const myMap = new Map() for (let c of myStr) { if (myMap.has(c)) { myMap.set(c, myMap.get(c)+1) } else { myMap.set(c, 1) } } for (let k of myMap.keys()) { console.log(`${k} occures ${myMap.get(k)} times`) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM