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

Leetcode Group Shifted Strings

时间:2015-10-11 11:30:10      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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.


解题思路:

关键点:group all strings that belong to the same shifting sequence, 所以找到属于相同移位序列的key 很重要。因此单独写了函数shiftStr, 

buffer.append((c - ‘a‘ - dist + 26) % 26 + ‘a‘) 极容易错。将相同移位序列的Strings存入key 对应的value中,建立正确的HashMap很重要。


Java code:

public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        if (strings == null) {
            throw new IllegalArgumentException("strings is null");
        }
        List<List<String>> result = new ArrayList<List<String>>();
        if(strings.length == 0){
            return result;
        }
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for(String str: strings) {
            String shifted_str = shiftStr(str);
            if(map.containsKey(shifted_str)){
                map.get(shifted_str).add(str);
            }else{
                List<String> item = new ArrayList<String>();
                item.add(str);
                map.put(shifted_str, item);
                result.add(item);
            }
        }
        for(List<String> list: result) {
            Collections.sort(list);
        }
        return result;
    }
    
    private String shiftStr(String str){
        StringBuilder buffer = new StringBuilder();
        char[] char_array = str.toCharArray();
        int dist = str.charAt(0) - ‘a‘;
        for(char c: char_array){
            buffer.append((c - ‘a‘ - dist + 26) % 26 + ‘a‘);
        }
        return buffer.toString();
    }
}

Reference:

1. https://leetcode.com/discuss/58003/java-solution-with-separate-shiftstr-function

 

Leetcode Group Shifted Strings

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4868855.html

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