Anagrams
Total Accepted: 33531 Total Submissions: 137666My Submissions
Question Solution
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题,涉及到C++的模板与容器的很多的内容,在本题中,题目的意思是找到那些字符串的字母一样只是顺序不同的那些字符串
而这样的话,采用hash表来做,我是将排好序的字符串作为键,而原始的字符串作为值,再在hash表中进行查找,计数
#include<iostream> #include<string> #include<map> #include<vector> #include<utility>//用到了pair的头文件 #include<algorithm>//用到了sort排序,的头文件 using namespace std; vector<string> anagrams(vector<string> &strs) { multimap<string,string> temp; vector<string> result_str; string str_temp; string str_temp2; int i=0; int len=strs.size(); while(i<len) { str_temp=strs[i]; str_temp2=strs[i]; sort(str_temp.begin(),str_temp.end());//将字符串进行排序 //temp.insert(pair<string,string>(str_temp,strs)); temp.insert(make_pair(str_temp,str_temp2));//将字符串排好序的做键值,原始的做值 //temp.insert(multimap<string,string>::value_type(str_temp,strs)); i++; } for(multimap<string,string>::iterator itr=temp.begin();itr!=temp.end();itr++) { if(temp.count(itr->first)>1)//查找所所有的键值个数多余1的的,将其值输出 result_str.push_back(itr->second); } return result_str; } int main() { string str1="asdf"; string str2="fdas"; string str3="dhfzxcx"; string str4="etbd"; vector<string> strs; strs.push_back(str1);strs.push_back(str2);strs.push_back(str3);strs.push_back(str4); vector<string> strs1; strs1=anagrams(strs); int i=0; int len=strs1.size(); while(i<len) { cout<<strs1[i]<<endl; i++; } system("pause"); return 1; }
时间: 2024-10-13 23:24:01