leetcode_49 字母异位分组
1. 题意
给定一个字符串的集合,根据字符串中含有字符种类和数目进行分类。
2. 题解
只要排序后的字符串是完全一样的,我们就可以认为它们属于同一类。
- 直接排序
class Solution1 {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {// string equal after sortstd::unordered_map< std::string, int> tpos;std::vector< std::vector<std::string> > ans;for (auto &str: strs) {std::array<int, 26> char_cnts{};for (auto c: str) {char_cnts[ c - 'a']++;}std::string tgStr;for (int i = 0;i < 26; ++i) {if ( char_cnts[i]) {tgStr.append( char_cnts[i], 'a' + i);}}if ( not tpos.count( tgStr )) {int pos = static_cast<int>( ans.size() );std::vector< std::string> vec;ans.emplace_back( vec );tpos[ tgStr ] = pos;}ans[ tpos[ tgStr ] ].push_back( str );}return ans;}
};
- 统计次数,构造排序后的字符串
class Solution {
public:vector<vector<string>> groupAnagrams(vector<string>& strs) {// string equal after sortstd::unordered_map< std::string, std::vector<std::string> > tpos;for (auto &str: strs) {std::string ps = str;std::sort(ps.begin(), ps.end());tpos[ps].push_back( str );}std::vector< std::vector<std::string> > ans;for (auto &[k,v]: tpos) {ans.emplace_back( v );}return ans;}
};