Finding repeated words on a string and counting the repetitions

后端 未结 29 940
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  野性不改
    2021-02-05 18:22

    You can use Prefix tree (trie) data structure to store words and keep track of count of words within Prefix Tree Node.

      #define  ALPHABET_SIZE 26
      // Structure of each node of prefix tree
      struct prefix_tree_node {
        prefix_tree_node() : count(0) {}
        int count;
        prefix_tree_node *child[ALPHABET_SIZE];
      };
      void insert_string_in_prefix_tree(string word)
      {
        prefix_tree_node *current = root;
        for(unsigned int i=0;i(word[i] - 'a');
    
          // Invalid alphabetic character, then continue
          // Note :::: Change this condition depending on the scenario
          if(letter > 26)
            throw runtime_error("Invalid alphabetic character");
    
          if(current->child[letter] == NULL)
            current->child[letter] = new prefix_tree_node();
    
          current = current->child[letter];
        }
      current->count++;
      // Insert this string into Max Heap and sort them by counts
    }
    
        // Data structure for storing in Heap will be something like this
        struct MaxHeapNode {
           int count;
           string word;
        };
    

    After inserting all words, you have to print word and count by iterating Maxheap.

提交回复
热议问题