LeetCode-Group Shifted Strings

Posted LiBlog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"],
A solution is:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
 
Solution:
public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> resLists = new LinkedList<List<String>>();
        
        HashMap<String,List<String>> patternMap = new HashMap<String,List<String>>();
        for (String str : strings){
            StringBuilder builder = new StringBuilder().append(str);
            int delta = builder.charAt(0)-‘a‘;
            builder.setCharAt(0,‘a‘);
            for (int i=1;i<builder.length();i++){
                char c = (char) ((builder.charAt(i) + 26 - delta)%26);
                builder.setCharAt(i,c);
            }
            String pattern = builder.toString();
            if (!patternMap.containsKey(pattern)){
                patternMap.put(pattern,new LinkedList<String>());
            }
            patternMap.get(pattern).add(str);
        }
        
        for (List<String> strList : patternMap.values()){
            resLists.add(strList);
        }
        return resLists;
    }
}

 

 

以上是关于LeetCode-Group Shifted Strings的主要内容,如果未能解决你的问题,请参考以下文章

Group Shifted Strings

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java

java 249. Group Shifted Strings.java