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"]

 

所谓的anagrams,就是某个单词打乱其字母顺序形成的新单词,新单词和原单词包含的字母种类相同,每个字母的数目相同。           本文地址

 

用哈希map存储排序后的字符串,map中key为排序后字符串,value为该字符串对应的第一个原字符串在数组中的位置。如果value = -1,表示该字符串对应的第一个源字符串已经输出过

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class  Solution {
public :
     vector<string> anagrams(vector<string> &strs) {
         typedef  unordered_map<string, int > Umap;
         Umap hashtable;
         vector<string> res;
         for ( int  i = 0; i < strs.size(); i++)
         {
             string s = strs[i];
             sort(s.begin(), s.end());
             Umap::iterator ite = hashtable.find(s);
             if (ite == hashtable.end())
                 hashtable.insert(Umap::value_type(s, i));
             else
             {
                 if (ite->second != -1)
                 {
                     res.push_back(strs[ite->second]);
                     ite->second = -1;
                 }
                 res.push_back(strs[i]);
             }
         }
         return  res;
     }
};





本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3681402.html,如需转载请自行联系原作者

目录
相关文章
LeetCode 438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter.
85 0
LeetCode 438. Find All Anagrams in a String
|
C语言 Python
LeetCode 49. Group Anagrams
给定一组字符串,将由相同字母组成的字符串组合在一起。 注意:所有给定的输入都是小写,输出的顺序不重要
69 0
|
存储 Java 索引
LeetCode 49: 字母异位词分组 Group Anagrams
# LeetCode 49: 字母异位词分组 Group Anagrams ### 题目: 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 Given an array of strings, group anagrams together.
731 0
|
存储 测试技术
(转)leetcode:Find All Anagrams in a String 滑动窗口方法总结
今天做了几道滑动窗口的题,稍微总结一下。 起因源于早上在leetcode上pick one,随机到了一个easy的题目,想着随便做了,结果半天也找不到最优解,耗时300多ms,A是A了,不过就是暴力罢了。
1696 0
[LeetCode]--49. Group Anagrams
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
1100 0
LeetCode - 49. Group Anagrams
49. Group Anagrams  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个由string类型构成的集合,让你按照每个字符串的单词构成集合来将这个集合分类.
979 0
[LeetCode] Group Anagrams
The function signature has been updated to return a more intuitive vectorwhich treats a single string as a group of anagrams consisting of only itself.
793 0
|
12天前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行