Se le proporciona una array de strings str[] , la tarea es encontrar la puntuación de una string dada de la array. La puntuación de una string se define como el producto de la suma de los valores alfabéticos de sus caracteres con la posición de la string en la array.
Ejemplos:
Entrada: str[] = {“sahil”, “shashanak”, “sanjit”, “abhinav”, “mohit”}, s = “abhinav”
Salida: 228
Suma de valores alfabéticos de “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57
La posición de “abhinav” en str es 4, 57 x 4 = 228
Entrada: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms”
Salida: 244
Enfoque:
en SET 1 , vimos un enfoque en el que cada vez que se ejecuta una consulta, la posición de la string debe encontrarse con un solo recorrido de str[] . Esto se puede optimizar cuando hay varias consultas que utilizan una tabla hash.
- Cree un mapa hash de todas las strings presentes en str[] junto con sus respectivas posiciones en la array.
- Luego, para cada consulta s , verifique si s está presente en el mapa. En caso afirmativo, calcule la suma de los valores alfabéticos de s y guárdelo en sum .
- Imprimir suma * pos donde pos es el valor asociado con s en el mapa, es decir, su posición en str[] .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the required string score int strScore(string str[], string s, int n) { // create a hash map of strings in str unordered_map<string, int> m; // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (m.find(s) == m.end()) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score; } // Driver code 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; }
Java
// Java implementation of the approach import java.util.HashMap; import java.util.Map; class GfG { // Function to return the required string score static int strScore(String str[], String s, int n) { // create a hash map of strings in str HashMap<String, Integer> m = new HashMap<>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m.put(str[i], i + 1); // If given string is not present in str[] if (!m.containsKey(s)) return 0; int score = 0; for (int i = 0; i < s.length(); i++) score += s.charAt(i) - 'a' + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver code 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)); } } // This code is contributed by Rituraj Jain
Python3
# Python3 implementation of the approach # Function to return the required # string score def strScore(string, s, n) : # create a hash map of strings in str m = {} # Store every string in the map # along with its position in the array for i in range(n) : m[string[i]] = i + 1 # If given string is not present in str[] if s not in m.keys() : return 0 score = 0 for i in range(len(s)) : score += ord(s[i]) - ord('a') + 1 # Multiply sum of alphabets # with position score = score * m[s] return score # Driver code if __name__ == "__main__" : string = [ "geeksforgeeks", "algorithms", "stack" ] s = "algorithms" n = len(string) score = strScore(string, s, n); print(score) # This code is contributed by Ryuga
C#
// C# implementation of the approach using System; using System.Collections.Generic; class GfG { // Function to return the required string score static int strScore(string [] str, string s, int n) { // create a hash map of strings in str Dictionary<string, int> m = new Dictionary<string, int>(); // Store every string in the map // along with its position in the array for (int i = 0; i < n; i++) m[str[i]] = i + 1; // If given string is not present in str[] if (!m.ContainsKey(s)) return 0; int score = 0; for (int i = 0; i < s.Length; i++) score += s[i] - 'a' + 1; // Multiply sum of alphabets with position score = score * m[s]; return score; } // Driver code public static void Main() { string [] str = { "geeksforgeeks", "algorithms", "stack" }; string s = "algorithms"; int n = str.Length; Console.WriteLine(strScore(str, s, n)); } } // This code is contributed by ihritik
Javascript
<script> // JavaScript Program to implement // the above approach // Function to return the required string score function strScore(str, s, n) { // create a hash map of strings in str let m = new Map(); // Store every string in the map // along with its position in the array for (let i = 0; i < n; i++) m.set(str[i], i + 1); // If given string is not present in str[] if (!m.has(s)) return 0; let score = 0; for (let i = 0; i < s.length; i++) score += s[i].charCodeAt() - 'a'.charCodeAt() + 1; // Multiply sum of alphabets with position score = score * m.get(s); return score; } // Driver Code let str = [ "geeksforgeeks", "algorithms", "stack" ]; let s = "algorithms"; let n = str.length; document.write(strScore(str, s, n)); </script>
244
Publicación traducida automáticamente
Artículo escrito por Sanjit_Prasad y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA