LeetCode 题解(245) : 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"],
Return:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

Note: For the return value, each inner list's elements must follow the lexicographic order.

题解:

给的例子太不具说明性了。应该举这个例子:

["eqdf", "qcpr"]。

((‘q’ - 'e') + 26) % 26 = 12, ((‘d’ - 'q') + 26) % 26 = 13, ((‘f’ - 'd') + 26) % 26 = 2

((‘c’ - 'q') + 26) % 26 = 12, ((‘p’ - 'c') + 26) % 26 = 13, ((‘r’ - 'p') + 26) % 26 = 2

所以"eqdf"和"qcpr"是一组shifted strings。

如此以来就很好理解了。我给你付费,你就给我举这么个例子,搞笑呢。

此题再次显现出Python语言的便捷。

C++版:

class Solution {
public:
    vector> groupStrings(vector& strings) {
        unordered_map> d;
        for(auto i : strings) {
            string s = "";
            for(auto j : i) {
                s += to_string(((j - i[0]) + 26) % 26) + " ";
            }
            if(d.find(s) != d.end()) {
                d[s].push_back(i);
            } else {
                vector v;
                v.push_back(i);
                d.insert(pair>(s, v));
            }
        }
        
        vector> result;
        for(auto i = d.begin(); i != d.end(); i++) {
            sort(i->second.begin(), i->second.end());
            result.push_back(i->second);
        }
        return result;
    }
};

Java版:

public class Solution {
    public List> groupStrings(String[] strings) {
        List> result = new ArrayList>();
        HashMap> d = new HashMap<>();
        for(int i = 0; i < strings.length; i++) {
            StringBuffer sb = new StringBuffer();
            for(int j = 0; j < strings[i].length(); j++) {
                sb.append(Integer.toString(((strings[i].charAt(j) - strings[i].charAt(0)) + 26) % 26));
                sb.append(" ");
            }
            String shift = sb.toString();
            if(d.containsKey(shift)) {
                d.get(shift).add(strings[i]);
            } else {
                List l = new ArrayList<>();
                l.add(strings[i]);
                d.put(shift, l);
            }
        }
        
        for(String s : d.keySet()) {
            Collections.sort(d.get(s));
            result.add(d.get(s));
        } 
        return result;
    }
}

Python版:

class Solution(object):
    def groupStrings(self, strings):
        """
        :type strings: List[str]
        :rtype: List[List[str]]
        """
        d = collections.defaultdict(list)
        for s in strings:
            shift = tuple([(ord(c) - ord(s[0])) % 26 for c in s])
            d[shift].append(s)
        
        return map(sorted, d.values())

你可能感兴趣的:(算法)