Group Shifted Strings simple Java Solutions: beats 99% accepted solutions


  • -2
    U

    public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
    List<List<String>> result = new ArrayList<>();
    if (strings == null || strings.length == 0)
    return result;
    HashMap<String, ArrayList<String>> map = new HashMap<>();
    for (String s : strings) {
    char []arr = s.toCharArray();
    int diff = arr[0] - 'a';
    for (int i=0; i<arr.length; i++) {
    arr[i] -= (char) diff;
    if (arr[i] < 'a') {
    arr[i] += 26;
    }
    }
    String key = new String(arr);
    ArrayList<String> value;
    if (map.containsKey(key)) {
    value = map.get(key);
    } else {
    value = new ArrayList<>();
    }
    value.add(s);
    map.put(key, value);
    }
    result.addAll(map.values());
    return result;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.