5ms Concise Java Solution


  • 0

    As jianchao.li.fighter mentioned in his post, "the key to this problem is how to identify strings that are in the same shifting sequence." They way I identified strings that were in the same shifting sequence, was by shifting a given string until the first character is 'a' (this is the key of the corresponding value in the hashmap). I.e., given "bcd," I would shift it:

    "bcd" -> "cde" -> ... -> "xyz" -> ... -> "abc"

    until I get back to the point where the first character is 'a'. Then, I will check the hashmap to see if this key is present. If it is, I add the string to the list associated with the key. If it is not present, I add a new ArrayList corresponding to this key. This is a similar strategy that I used in Valid Anagram.

    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            Map<String, List<String>> hm = new HashMap<String, List<String>>();
            List<List<String>> res = new ArrayList<List<String>>();
            for(String s: strings) {
                String aShift = getAShift(s);
                if(hm.containsKey(aShift)) hm.get(aShift).add(s);
                else hm.put(aShift, new ArrayList<String>(Arrays.asList(s)));
            }
            
            for(List<String> value: hm.values()) res.add(value);
            return res;
        }
        
        public String getAShift(String s) {
            char[] chary = s.toCharArray();
            while(chary[0] != 97) {
                for(int i = 0; i < chary.length; i++) {
                    chary[i] = chary[i] == 'z' ? 'a' : (char) (chary[i] + 1);
                }
            }
            return new String(chary);
        }
    }
    

Log in to reply
 

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