Around 13 lines code in java


  • 6
    C
     public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            
            List<List<String>> res = new ArrayList<List<String>>();
            HashMap<String, List<String>> map = new HashMap<String, List<String>>();
            
            for(String word : strings){
                String key = "";
                int offset = word.charAt(0) - 'a';
                for(int i = 1; i < word.length(); i++){
                    key += (word.charAt(i) - offset + 26) % 26;
                }
                
                if(!map.containsKey(key)){
                    map.put(key, new ArrayList<String>());
                }
                map.get(key).add(word);
            }
            
            for(List<String> list : map.values()){
                Collections.sort(list);
                res.add(list);
            }
            
            return res;
            
        }
    }

  • 0
    R

    Actually I think you cannot use 0-9 to represent the pattern. You still need the a-z to represent the pattern.
    Your code would fail ["abc", "al"].


  • 0
    C

    Can you explain more? I don't think it fails.


  • 0
    R

    For ["abc", "al"] your code gives the same pattern 11 so that you group them into the same group, actually they are not. What do you think?


  • 0
    C

    You are right. I have made update


  • 0
    I

    no need to plus 26


Log in to reply
 

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