Leetcode 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.


解题思路:

关键点: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

 

posted @ 2015-10-11 10:05  茜茜的技术空间  阅读(867)  评论(0编辑  收藏  举报