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

[LeetCode] 249. Group Shifted Strings 分组偏移字符串

时间:2018-04-06 15:19:18      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:cut   empty   app   code   must   解法   pst   lse   param   

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.

一个字符串可以通过偏移变成另一个字符串,比如 ‘abc’ –> ‘bcd’ (所有字母右移一位),把可通过偏移转换的字符串归为一组。给定一个 String 数组,返回分组结果。

解法:将每个字符串都转换成减去字符串首字符之后的字符串,这样可以相互转换的字符串就转化成了一个key,然后用map将以这个key保存所有可以相互转换字符串的集合。

满足条件: S.length = T.length and S[i] = T[i] + K for  1 <= i <= S.length for a constant integer K

Java:

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:

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++:  

class Solution {
public:
    int longestConsecutive(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int len = 1;
            TreeNode *t = q.front(); q.pop();
            while ((t->left && t->left->val == t->val + 1) || (t->right && t->right->val == t->val + 1)) {
                if (t->left && t->left->val == t->val + 1) {
                    if (t->right) q.push(t->right);
                    t = t->left;
                } else if (t->right && t->right->val == t->val + 1) {
                    if (t->left) q.push(t->left);
                    t = t->right;
                }
                ++len;
            }
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
            res = max(res, len);
        }
        return res;
    }
};

  

类似题目:

[LeetCode] 49. Group Anagrams 分组变位词 

[LeetCode] 300. Longest Increasing Subsequence 最长递增子序列

 

 

[LeetCode] 249. Group Shifted Strings 分组偏移字符串

标签:cut   empty   app   code   must   解法   pst   lse   param   

原文地址:https://www.cnblogs.com/lightwindy/p/8727587.html

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