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

Group Shifted Strings -- LeetCode

时间:2016-08-14 13:06:05      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:

"abc" -> "bcd" -> ... -> "xyz"

Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
A solution is:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
 1 class Solution {
 2 public:
 3     string help(string word) {
 4         for (int i = 1, n = word.size(); i < n; i++) {
 5             word[i] = word[i] - word[0] + a;
 6             while (word[i] < a) word[i] += 26;
 7         }
 8         word[0] = a;
 9         return word;
10     }
11     vector<vector<string>> groupStrings(vector<string>& strings) {
12         unordered_map<string, int> dict;
13         vector<vector<string> > res;
14         for (int i = 0, n = strings.size(); i < n; i++) {
15             string base = help(strings[i]);
16             if (dict.count(base) == 0) {
17                 dict.insert(make_pair(base, res.size()));
18                 vector<string> subGroup(1, strings[i]);
19                 res.push_back(subGroup);
20             }
21             else res[dict[base]].push_back(strings[i]);
22         }
23         return res;
24     }
25 };

 

Group Shifted Strings -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5769925.html

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