[LeetCode] 249. 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:html

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

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

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
Return:python

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

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

一個字符串能夠經過偏移變成另外一個字符串,好比 ‘abc’ –> ‘bcd’ (全部字母右移一位),把可經過偏移轉換的字符串歸爲一組。給定一個 String 數組,返回分組結果。app

解法:將每一個字符串都轉換成與字符串首字符ASCII碼值差的字符串,好比:'abc'就轉換成'012','bcd'轉換成了'012',兩個就是同組的偏移字符串。用Hashmap來統計,key就是轉換後的數字字符串,value是全部能夠轉換成此key的字符串集合。spa

注意:這個差值多是負的,說明後面的字符比前面的小,此時加上26。code

Java:orm

class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> result = new ArrayList<List<String>>();
        HashMap<String, ArrayList<String>> map 
                        = new HashMap<String, ArrayList<String>>();

        for(String s: strings){
            char[] arr = s.toCharArray();
            if(arr.length>0){
                int diff = arr[0]-'a';
                for(int i=0; i<arr.length; i++){
                    if(arr[i]-diff<'a'){
                       arr[i] = (char) (arr[i]-diff+26);
                    }else{
                       arr[i] = (char) (arr[i]-diff); 
                    }

                }
            }  

            String ns = new String(arr);
            if(map.containsKey(ns)){
                map.get(ns).add(s);
            }else{
                ArrayList<String> al = new ArrayList<String>();
                al.add(s);
                map.put(ns, al);
            }
        }

        for(Map.Entry<String, ArrayList<String>> entry: map.entrySet()){
            Collections.sort(entry.getValue());
        }

        result.addAll(map.values());

        return result;
    }
}

Python: Time: O(nlogn), Space: O(n)htm

import collections

class Solution:
    # @param {string[]} strings
    # @return {string[][]}
    def groupStrings(self, strings):
        groups = collections.defaultdict(list)
        for s in strings:  # Grouping.
            groups[self.hashStr(s)].append(s)

        result = []
        for key, val in groups.iteritems():
            result.append(sorted(val))

        return result

    def hashStr(self, s):
        base = ord(s[0])
        hashcode = ""
        for i in xrange(len(s)):
            if ord(s[i]) - base >= 0:
                hashcode += unichr(ord('a') + ord(s[i]) - base)
            else:
                hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
        return hashcode

C++:  blog

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        vector<vector<string> > res;
        unordered_map<string, multiset<string>> m;
        for (auto a : strings) {
            string t = "";
            for (char c : a) {
                t += to_string((c + 26 - a[0]) % 26) + ",";
            }
            m[t].insert(a);
        }
        for (auto it = m.begin(); it != m.end(); ++it) {
            res.push_back(vector<string>(it->second.begin(), it->second.end()));
        }
        return res;
    }
};  

  

相似題目:

[LeetCode] 49. Group Anagrams 分組變位詞 

[LeetCode] 300. Longest Increasing Subsequence 最長遞增子序列

 

All LeetCode Questions List 題目彙總

相關文章
相關標籤/搜索