**一. 题目描述**
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
**二. 题目分析**
Anagram(回文构词法)是指打乱字母顺序从而得到新的单词,比如”dormitory” 打乱字母顺序会变成”dirty room” ,”tea” 会变成”eat”。
回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。
因此,将几个单词按照字母顺序排序后,若它们相等,则它们属于同一组anagrams 。
**三. 示例代码**
~~~
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
string s;
map<string, int> anagram;
vector<string> res;
for (int i = 0; i < strs.size(); ++i) {
s = strs[i];
sort(s.begin(), s.end());
if (anagram.find(s) == anagram.end()) {
anagram[s] = i;
} else {
if (anagram[s] >= 0) {
res.push_back(strs[anagram[s]]);
anagram[s] = -1;
}
res.push_back(strs[i]);
}
}
return res;
}
};
~~~
**四. 小结**
这里关键在于对题目的理解。本文中anagrams指只有字母排列顺序不同的单词,例如eat,ate,tea。这个问题就可以使用hash的方法来解决,也有很多种不同的hash方法。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016腾讯软件开发笔试题)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契数列问题)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波兰式的计算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和问题)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching