Group Shifted Strings

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Group Shifted Strings相关的知识,希望对你有一定的参考价值。

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

 

Analyse: keep the diff between each character in the string. Put the strings with same diff in the same vector.

Runtime: 6ms

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupStrings(vector<string>& strings) {
 4         unordered_map<string, vector<string> > groups;
 5         for (string s : strings) {
 6             if (s.size() == 1) {
 7                 groups["-"].push_back(s);
 8             } else {
 9                 string tempGap;
10                 for (int i = 1; i < s.size(); i++) {
11                     if (s[i] > s[i - 1])
12                         tempGap += to_string(s[i] - s[i - 1]);
13                     else
14                         tempGap += to_string(26 + (s[i] - s[i - 1]));
15                 }
16                 groups[tempGap].push_back(s);
17             }
18         }
19         
20         vector<vector<string> > result;
21         for (auto ite = groups.begin(); ite != groups.end(); ite++) {
22             vector<string> tempStrings = ite->second;
23             result.push_back(vector<string>());
24             for (auto s : tempStrings) {
25                 result.back().push_back(s);
26             }
27         }
28         return result;
29     }
30 };

 

以上是关于Group Shifted Strings的主要内容,如果未能解决你的问题,请参考以下文章

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

249.Group Shifted Strings