leetcode 49: anagrams

leetcode-anagrams

// leetcode 49: 将由相同字母组成的字符串进行分类
// 解题思路:将字符串进行排序,排序完一样的字符串归为一类
// 使用map来对字符串进行归类,最后转换为vector二维数组
// 本题不要求最后输出的顺序

#include 
#include 
#include 
#include 
using namespace std;

string sortStr(string str) {
	// 注意初始化
	int count[26] = { 0 };
	int n = str.size();
	for (int i = 0; i < n;++i) {
		count[str[i] - 'a']++;
	}
	string res = "";
	for (int i = 0; i < 26; ++i) {
		res += string(count[i], i + 'a');
	}
	return res;
}

vector> groupAnagrams(vector& strs) {
	vector> result;
	unordered_map> dataset;
	int n = strs.size();
	for (int i = 0; i < n; ++i) {
		dataset[sortStr(strs[i])].push_back(strs[i]);
	}
	for (auto data : dataset) {
		result.push_back(data.second);
	}
	return result;
}

int main() {
	vector data;
	int n;
	cin >> n;
	string str;
	for (int i = 0; i < n; ++i) {
		cin >> str;
		data.push_back(str);
	}
	vector> res = groupAnagrams(data);
	int len1 = res.size();
	for (int i = 0; i < len1; ++i) {
		for (int j = 0; j < res[i].size(); ++j) {
			cout << res[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(leetcode)