문자열 또는 배열에서 문자의 빈도를 찾는 방법

이 게시물에서는 문자열이나 배열에서 문자의 빈도를 찾는 방법을 기술할 것입니다. 이것은 인터뷰에서 자주 묻는 질문입니다. Java 및 JavaScript 코드에 대해 설명하겠습니다.

질문 프롬프트



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



이것은 문자열이나 배열에서 문자의 빈도를 얻는 방법입니다. 질문이 있으시면 의견 섹션에 알려주십시오. 이와 같은 콘텐츠를 더 원하신다면 저를 팔로우하는 것도 고려해보세요.

좋은 웹페이지 즐겨찾기