LeetCode-49. 字母异位词分组

本文介绍了一种解决字母异位词分组问题的算法,通过字符串ASCII码排序和unordered_map双层映射实现字符串分组,有效处理了字符串数组中字母相同但排列不同的字符串分组问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

49. 字母异位词分组

难度中等207收藏分享切换为英文关注

通过次数

35,503

提交次数

59,957

题目描述

评论 (223)

题解(59)New

提交记录

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

 

 

好久没有一次过了。思路非常简单,一个字符串ascall码排序

和unorder_map的两层映射去重!渣渣用的排序是冒泡排序.....

#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
#include <unordered_map>
using namespace std;


/* 建立两层映射关系 */
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<string> strList;
        vector<string>::iterator it = strs.begin();
        while(it!=strs.end()){
            string temp = GetSort(*it);
            m_map[temp].push_back(*it);

            /* 去重 */
            if(m_count.count(temp)==0){
                m_count[temp] = temp;
                strList.push_back(temp);
            }
            it++;
        }

        vector<vector<string>> res;
        vector<string>::iterator VecTemp = strList.begin();
        while(VecTemp!=strList.end()){
            //            cout<<"VecTemp:"<<(*VecTemp)<<endl;
            res.push_back(m_map[*VecTemp]);
            VecTemp++;
        }
        return res;
    }
private:
    unordered_map<string,vector<string>> m_map;
    unordered_map<string,string> m_count;
    string GetSort(string value);
};

/* 判断是否为相同字符串 */
string Solution::GetSort(string value){
    string res;
    char dest[256] = {'\0'};
    int len = value.length();
    strcpy(dest,value.c_str());
    for(int i=0;i<len-1;i++){
        for(int j=0;j<len-i-1;j++){
            if(dest[j]>dest[j+1]){
                char temp = dest[j];
                dest[j] = dest[j+1];
                dest[j+1] = temp;
            }
        }
    }
    res = dest;
    cout<<"dest:"<<res<<endl;
    return res;
}


int main(){
    vector<string> Vec = {"eat", "tea", "tan", "ate", "nat", "bat"};
    Solution *ps = new Solution();
    vector<vector<string>> res = ps->groupAnagrams(Vec);

    vector<vector<string>>::iterator it = res.begin();
    while(it!=res.end()){
        vector<string>::iterator base = (*it).begin();
        cout<<"list:";
        while(base!=((*it).end())){
            cout<<*base<<" ";
            base++;
        }
        cout<<endl;
        it++;
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值