Weighted sum of the characters of a string in an array | Set 2 | C ++ implementation of the approach ; Function to return the required string score ; create a hash map of strings in str ; Store every string in the map along with its position in the array ; If given string is not present in str [ ] ; Multiply sum of alphabets with position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int strScore ( string str [ ] , string s , int n ) { unordered_map < string , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ str [ i ] ] = i + 1 ; if ( m . find ( s ) == m . end ( ) ) return 0 ; int score = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) score += s [ i ] - ' a ' + 1 ; score = score * m [ s ] ; return score ; } int main ( ) { string str [ ] = { " geeksforgeeks " , " algorithms " , " stack " } ; string s = " algorithms " ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; int score = strScore ( str , s , n ) ; cout << score ; return 0 ; }