📜  使用自定义哈希函数对数组中的字符串进行分类

📅  最后修改于: 2021-05-14 00:15:40             🧑  作者: Mango

给定字符串数组ARR []N字符串,任务是根据通过将ASCII值%26字符串中的字符的获得的散列值进行分类的字符串。

例子:

方法:想法是使用“地图数据结构”将具有相同哈希值的字符串分组在一起。请按照以下步骤解决问题:

  • 初始化一个映射,例如mp ,以将哈希值与向量中的各个字符串映射。
  • 遍历给定的字符串数组并执行以下步骤:
    • 计算哈希值 根据给定函数的当前字符串。
    • 将字符串推入向量,并使用计算出的字符串哈希值作为映射mp中的
  • 最后,遍历map mp并打印各个键的所有字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the hash
// value of the string s
int stringPower(string s)
{
    // Stores hash value of string
    int power = 0;
    int n = s.length();
 
    // Iterate over characters of the string
    for (int i = 0; i < n; i++) {
 
        // Calculate hash value
        power = (power + (s[i])) % 26;
    }
 
    // Return the hash value
    return power;
}
 
// Function to classify the strings
// according to the given condition
void categorisation_Of_strings(
    vector s, int N)
{
    // Maps strings with their strings
    // respective hash values
    map > mp;
 
    // Traverse the array of strings
    for (int i = 0; i < N; i++) {
 
        // Find the hash value of the
        // of the current string
        int temp = stringPower(s[i]);
 
        // Push the current string in
        // value vector of temp key
        mp[temp].push_back(s[i]);
    }
 
    // Traverse over the map mp
    for (auto power : mp) {
 
        // Print the result
        for (auto str : power.second) {
            cout << str << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    vector arr{ "adf", "aahe",
                        "bce", "bgdb" };
    int N = arr.size();
 
    categorisation_Of_strings(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
 
class GFG{
     
// Function to find the hash
// value of the string s
static int stringPower(String s)
{
     
    // Stores hash value of string
    int power = 0;
    int n = s.length();
    char C[] = s.toCharArray();
 
    // Iterate over characters of the string
    for(int i = 0; i < n; i++)
    {
         
        // Calculate hash value
        power = (power + (C[i])) % 26;
    }
 
    // Return the hash value
    return power;
}
 
// Function to classify the strings
// according to the given condition
static void categorisation_Of_strings(Vector s,
                                      int N)
{
     
    // Maps strings with their strings
    // respective hash values
    Map > mp = new HashMap<>();
     
    // Traverse the array of strings
    for(int i = 0; i < N; i++)
    {
         
        // Find the hash value of the
        // of the current string
        int temp = stringPower(s.get(i));
 
        // Push the current string in
        // value vector of temp key
        if (mp.containsKey(temp))
        {
            mp.get(temp).add(s.get(i));
        }
        else
        {
            mp.put(temp, new Vector());
            mp.get(temp).add(s.get(i));
        }
    }
 
    // Traverse over the map mp
    for(Map.Entry> entry : mp.entrySet())
    {
         
        // Print the result
        for(String str : entry.getValue())
        {
            System.out.print(str + " ");
        }
        System.out.println();
    }
}
 
// Driver code
public static void main(String[] args)
{
    String[] Sarr = { "adf", "aahe", "bce", "bgdb" };
    Vector arr = new Vector(
        Arrays.asList(Sarr));
    int N = arr.size();
 
    categorisation_Of_strings(arr, N);
}
}
 
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
 
# Function to find the hash
# value of the string s
def stringPower(s):
   
    # Stores hash value of string
    power = 0
    n = len(s)
 
    # Iterate over characters of the string
    for i in range(n):
       
        # Calculate hash value
        power = (power + ord(s[i])) % 26
 
    # Return the hash value
    return power
 
# Function to classify the strings
# according to the given condition
def categorisation_Of_strings(s, N):
   
    # Maps strings with their strings
    # respective hash values
    mp = {}
 
    # Traverse the array of strings
    for i in range(N):
       
        # Find the hash value of the
        # of the current string
        temp = stringPower(s[i])
 
        # Push the current string in
        # value vector of temp key
        if temp in mp:
            mp[temp].append(s[i])
        else:
            mp[temp] = []
            mp[temp].append(s[i])
             
    # Traverse over the map mp
    for i in sorted (mp) :
       
        # Print the result
        for str in mp[i]:
            print(str,end = " ")
        print("\n",end = "")
 
# Driver Code
if __name__ == '__main__':
    arr =  ["adf", "aahe", "bce", "bgdb"]
    N = len(arr)
    categorisation_Of_strings(arr, N)
 
    # This code is contributed by ipg2016107.


输出:
aahe bgdb 
bce 
adf

时间复杂度: O(N * M),其中M是最长字符串的长度。
辅助空间: O(N * M)