Frequency of a string in an array of strings | C ++ program to count number of times a string appears in an array of strings ; To store number of times a string is present . It is 0 is string is not present ; function to insert a string into the Trie ; calculation ascii value ; If the given node is not already present in the Trie than create the new node ; Returns count of occurrences of s in Trie ; inserting in Trie ; searching the strings in Trie ; Driver code
#include <iostream> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; struct Trie { int cnt ; Trie * node [ MAX_CHAR ] ; Trie ( ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) node [ i ] = NULL ; cnt = 0 ; } } ; Trie * insert ( Trie * root , string s ) { Trie * temp = root ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = s [ i ] - ' a ' ; if ( ! root -> node [ index ] ) root -> node [ index ] = new Trie ( ) ; root = root -> node [ index ] ; } root -> cnt ++ ; return temp ; } int search ( Trie * root , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = s [ i ] - ' a ' ; if ( ! root -> node [ index ] ) return 0 ; root = root -> node [ index ] ; } return root -> cnt ; } void answerQueries ( string arr [ ] , int n , string q [ ] , int m ) { Trie * root = new Trie ( ) ; for ( int i = 0 ; i < n ; i ++ ) root = insert ( root , arr [ i ] ) ; for ( int i = 0 ; i < m ; i ++ ) cout << search ( root , q [ i ] ) << " ▁ " ; } int main ( ) { string arr [ ] = { " aba " , " baba " , " aba " , " xzxb " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string q [ ] = { " aba " , " xzxb " , " ab " } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; answerQueries ( arr , n , q , m ) ; return 0 ; }