---
# System prepended metadata

title: 0249. Group Shifted Strings
tags: [Leetcode, FaceBook, Medium]

---

# 0249. Group Shifted Strings
###### tags: `Leetcode` `Medium` `FaceBook`
Link: https://leetcode.com/problems/group-shifted-strings/
## 思路
用HashMap存编码出的key以及对应的list idx
key的编码方式：以第一个字母为标杆，第一个字母对应的ASCII码为num，后面每一位都减去这个num，再存进去
要注意findKey里面每个字符转换的算式，一定要+26，因为如果字符串是"ba"，那么diff = 1，算到a的时候str.charAt(i)-diff-'a'=-1，**-1%26还是-1**，不能把这个字符变成'z'
## Code
```java=
class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        Map<String, List<String>> map = new HashMap<>();
        for(String str:strings){
            String convertStr = findKey(str);
            if(!map.containsKey(convertStr)){
                map.put(convertStr, new ArrayList<>());
            }
            map.get(convertStr).add(str);
        }
        List<List<String>> ans = new ArrayList<>();
        for(List<String> list:map.values()){
            ans.add(list);
        }
        return ans;
    }
    private String findKey(String str){
        int diff = str.charAt(0)-'a';
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i < str.length();i++){
            sb.append((char)((str.charAt(i)-diff-'a'+26)%26+'a'));
        }
        return sb.toString();
    }
}
```
## Result
Runtime: 1 ms, faster than **100.00%** of Java online submissions for Group Shifted Strings.
Memory Usage: 39.1 MB, less than **82.84%** of Java online submissions for Group Shifted Strings.