leetcode 49. Group Anagrams【素数相乘处理字符串哈希】

https://leetcode.com/problems/group-anagrams/description/

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

rt

寻找的是交换位置后字符串一样的

关键在于如何哈希

查了半天

看了题解才想起来

将所有字符对应成一个素数

那么相乘之后的值就是可以唯一表示的

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        long long num[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113};
        vector<long long>ans;
        vector<vector<string>> ana;
        for(int i=0;i<strs.size();i++){
            long long tot=1;
            for(int j=0;j<strs[i].length();j++)
                tot*=num[strs[i][j]-'a'];
            bool flag=1;
            for(int j=0;j<ans.size()&&flag;j++){
                if(ans[j]==tot)
                    flag=false,ana[j].push_back(strs[i]);
            }
           // printf("tot=%lld\n",tot);
            if(flag==1){
                ans.push_back(tot);
                vector<string>tmps;
                tmps.push_back(strs[i]);
                ana.push_back(tmps);
            }
                
        }
        return ana;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值