Thursday, April 8, 2021

Group Shifted Strings

 We can shift a string by shifting each of its letters to its successive letter.

  • For example, "abc" can be shifted to be "bcd".

We can keep shifting the string to form a sequence.

  • For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz".

Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

 

Example 1:

Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]
Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]

Example 2:

Input: strings = ["a"]
Output: [["a"]]

 

Constraints:

  • 1 <= strings.length <= 200
  • 1 <= strings[i].length <= 50
  • strings[i] consists of lowercase English letters.

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        // base cases later
        unordered_map<string, vector<string>> mp;
        vector<vector<string>> ans;
        for (auto str : strings) {
            mp[Hash(str)].push_back(str);
        }

        for (auto entry : mp) {
            ans.push_back(entry.second);
        }
        
        return ans;
    }
    
    string Hash(string str) {
        int size = str.size();
        if (size == 0) {
            return "-";
        }
        if (size == 1) {
            return "";
        }
        string code;
        for (int i = 0; i < size - 1; i++) {
            int diff = str[i + 1] - str[i];
            diff = (diff + 26) % 26;
            if (code.empty()) {
                code = to_string(diff);
            } else {
                code += "-" + to_string(diff);
            }
        }
        return code;
    }
};

No comments:

Post a Comment