首页 > 其他 > 详细

LeetCode – Refresh – Anagrams

时间:2015-03-18 07:47:29      阅读:213      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!