Weighted sum of the characters of a string in an array | Set 2 | Java 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
import java . util . HashMap ; import java . util . Map ; class GfG { static int strScore ( String str [ ] , String s , int n ) { HashMap < String , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) m . put ( str [ i ] , i + 1 ) ; if ( ! m . containsKey ( s ) ) return 0 ; int score = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) score += s . charAt ( i ) - ' a ' + 1 ; score = score * m . get ( s ) ; return score ; } public static void main ( String [ ] args ) { String str [ ] = { " geeksforgeeks " , " algorithms " , " stack " } ; String s = " algorithms " ; int n = str . length ; System . out . println ( strScore ( str , s , n ) ) ; } }