문자열 또는 배열에서 문자의 빈도를 찾는 방법
질문 프롬프트
Write a function, charFrequency, that takes in a string/array as an argument. The function should return the the frequency of each character in the string/array then return the answer as map or dictionary.
You can assume that the input string is non-empty.
example_00
mostFrequentChar('david'); -> Map={ 'd' => 2, 'a' => 1, 'v' => 1, 'i' => 1 }
예_01:
mostFrequentChar('bookeeper'); // -> Map= { 'b' => 1, 'o' => 2, 'k' => 1, 'e' => 3, 'p' => 1, 'r' => 1 }
자바스크립트 솔루션
const charFrequency = (str) => {
//create a map to save the characters and save the frequency of each character
const frequencyMap = new Map();
//go through each character in the string 'str'
for(let char of str)
{
//check if our map doesn't contain the current character we are going through
if(!frequencyMap.has(char))
{
//if our map doesn't contain the character we add it and assign the frequency to 1
frequencyMap.set(char,1);
}
//check if our map does contain the current character
else
{
// if our map contains the current character we are going to add 1 to the character frequency value
//example, if we had 'd' => 1, we are going to get the value of 'd' and add 1 to it
// so 'd' frequency value beacomes 2
frequencyMap.set(char,frequencyMap.get(char)+1);
}
}
//return the frequencyMap we created
return frequencyMap;
}
자바 솔루션
public String frequencySort(String str) {
//create a map to save the characters and save the frequency of each character
HashMap<Character,Integer> frequencyMap = new HashMap();
//go through the string 'str'
for(char ch : str.toCharArray())
{
//check if our map contains the current character we are going through
if(!frequencyMap.containsKey(ch))
{
//if our map doesn't contain the character we add it and assign the frequency to 1
frequencyMap.put(ch,1);
}
//check if our map does contain the current character
else
{
// if our map contains the current character we are going to add 1 to the character frequency value
//example, if we had 'd' => 1, we are going to get the value of 'd' and add 1 to it
// so 'd' frequency value beacomes 2
frequencyMap.put(ch,frequencyMap.get(ch)+1);
}
}
//return the frequencyMap we created
return frequencyMap;
}
이것은 문자열이나 배열에서 문자의 빈도를 얻는 방법입니다. 질문이 있으시면 의견 섹션에 알려주십시오. 이와 같은 콘텐츠를 더 원하신다면 저를 팔로우하는 것도 고려해보세요.
Reference
이 문제에 관하여(문자열 또는 배열에서 문자의 빈도를 찾는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/gilfoyle/how-to-find-the-frequency-of-characters-in-a-string-or-array-3271텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)