Java solution using java 8 groupingBy


  • -1
    F

    For each string we calculate their signature. java 8 groupingBy can eliminate boilerplate code

    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> r = new ArrayList<>();
            if(strings== null || strings.length==0){
                return r;
            }
            Arrays.sort(strings);
            r.addAll(Arrays.stream(strings).collect(Collectors.groupingBy(x->computeSig(x))).values());
            return r;
        }
        
        private String computeSig(String s){
            StringBuilder sb = new StringBuilder();
            char dist = (char)(s.charAt(0)-'a');
            for(int i=0;i<s.length();i++){
                char computed = (char)(s.charAt(i)-dist);
                if(computed<'a'){
                    computed = (char) ('z'+1+ (computed-'a'));
                }
                sb.append(computed);
            }
            return sb.toString();
        }
    }

Log in to reply
 

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