码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Anagrams

时间:2015-03-18 07:47:38      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

Use a hash table to record it. The tricky part is that when the hash value is > 0, it is the index + 1. Otherwise, that string already exists in result list.

 

 1 class Solution {
 2 public:
 3     vector<string> anagrams(vector<string> &strs) {
 4         vector<string> result;
 5         int len = strs.size();
 6         if (len < 2) return result;
 7         unordered_map<string, int> mapping;
 8         for (int i = 0; i < len; i++) {
 9             string tmp = strs[i];
10             sort(tmp.begin(), tmp.end());
11             if (mapping[tmp]) {
12                 if (mapping[tmp] > 0) {
13                     result.push_back(strs[mapping[tmp]-1]);
14                     mapping[tmp] = -1;
15                 }
16                 result.push_back(strs[i]);
17             } else {
18                 mapping[tmp] = i+1;
19             }
20         }
21         return result;
22     }
23 };

 

LeetCode – Refresh – Anagrams

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!