簡體   English   中英

查找字符串中的唯一字符及其出現次數

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

我需要計算給定字符串中字符的出現次數並打印出唯一字符以及它們出現的次數。 因此,例如,如果我收到一串“HELLO”,它應該打印出來:

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

這是一個問題的簡化版本,但答案應該讓我朝着正確的方向前進。 我該如何解決這個問題?

先感謝您。

這或多或少應該是它的樣子,以便更容易以 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}

您可以使用Array.reduce()來獲取輸入單詞中每次出現的計數。

我們使用 ... 運算符將單詞轉換為數組,然后使用 .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; }

我解決這個問題的方法是:

 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);

也許最簡單的答案就是拆分為 char 並將其放入地圖中。

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

count是你想要的。

使用像數據結構這樣的字典,它可以為您提供O(1)訪問和更新時間。 在 JS 中,您可以使用 Object literat(不推薦)或Map

遍歷字符串的字符並通過增加當前字符的字符數來更新字典。 如果它不在您的字典中,請將其添加並將計數設置為 1。

完成迭代后,迭代字典的鍵,其中值是該特定字符的出現次數,並以您喜歡的任何格式輸出它們。

 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