leetcode #49 in cpp

本文介绍了一种用于将字符串数组中的字母异位词进行分组的高效算法。通过使用哈希映射来跟踪每个已排序字符串对应的组编号,可以确保所有字母异位词被正确地分到同一组中。此外,文章还提供了详细的实现步骤和代码示例。

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

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.


Solution: 

1. To determine if one is anagram of another, we can sort both and compare if their sorted outputs are the same. 

2. To keep track if a string belongs to a group, ew use a hash map. If the sorted string is found in the map, then it belongs to a group. The value of the map can be the number of the group the string belongs to. 

2. The maintain order, we first sort the original input. In this way we scan through strings with lexical order. And strings would be pushed into final result in lexical order.


Code: 

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string, int> mapp;
        vector<int> group_ind(strs.size());
        sort(strs.begin(), strs.end());//maintain order in output
        int group_count = 0;//counting how many groups
        for(int i = 0; i < strs.size(); i++){
            string s = strs[i];
            sort(s.begin(), s.end());//sort the string 
            if(mapp.find(s)==mapp.end()){//if the string could not be found, create a new group
                mapp[s] = group_count;//note the group number for the set of this string 
                group_ind[i] = group_count;//note the group number for current string
                group_count++;
            }
            else
                group_ind[i] = mapp[s];//note the group number for current string 
                    
        }
        
        vector<vector<string>> res(group_count);
        for(int i = 0; i < strs.size(); i ++){
            res[group_ind[i]].push_back(strs[i]);
        }
        return res;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值