leetcode:字符串之Anagrams

leetcode:字符串之Anagrams

題目:

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.

For example,

Input:  ["tea","and","ate","eat","den"]

Output:   ["tea","ate","eat"]

即:找出符合迴文構詞法的詞。

Anagram(迴文構詞法)是指打亂字母順序從而得到新的單詞,比如"dormitory" 打亂字母順序會變成"dirty room" ,"tea" 會變成"eat"。
迴文構詞法有一個特點:單詞裏的字母的種類和數目沒有改變,只是改變了字母的排列順序。因此,將幾個單詞按照字母順序排序後,若它們相等,則它們屬於同一組anagrams 。

C++實現;

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <map>

using namespace std;
vector<string> anagrams(vector<string> &strs) 
{
	unordered_map<string, vector<string> > group;

    for (const auto &s : strs) 
	{
		string key = s;
        sort(key.begin(), key.end());
        group[key].push_back(s);
    }
    vector<string> result;

    for (auto it = group.cbegin(); it != group.cend(); it++) 
	{
		if (it->second.size() > 1)
        result.insert(result.end(), it->second.begin(), it->second.end());
    }

    return result;
}
int main()
{
	string word[]={"tea","and","ate","eat","den"};
    size_t s_count=sizeof(word)/sizeof(string);
    vector<string> svec(word,word+s_count);

	vector<string>::iterator it;
	for(it=svec.begin();it!=svec.end();it++)
		cout<<*it<<" ";
	cout<<endl;

	vector<string> re_svec;

	re_svec=anagrams(svec);

	vector<string>::iterator it1;
	for(it1=re_svec.begin();it1!=re_svec.end();it1++)
		cout<<*it1<<" ";
	cout<<endl;

	return 0;
}
測試結果;




發佈了68 篇原創文章 · 獲贊 78 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章