Need to add a new testcase: ["abc","al"]


  • 0
    C

    Generating key by simply appending the difference between char will fail for case like ["abc","al"].

    "abc" -> "11"
    "al" -> "11"

    My AC solution clearly won't work for case like that.

    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for (String s : strings) {
                String key = "";
                if (s.length() == 0) {
                    key = "zero";
                } else if (s.length() == 1) {
                    key = "one";
                } else {
                    for (int i = 0; i < s.length() - 1; i++) {
                        int distance = s.charAt(i + 1) - s.charAt(i);
                        if (distance < 0) {
                            distance += 26;
                        }
                        key += distance; // "AC" solution!
                        // the right solution should be like
                        // key += "," + distance;
                    }
                }
                
                if (map.containsKey(key)) {
                    map.get(key).add(s);
                } else {
                    List<String> group = new ArrayList<String>();
                    group.add(s);
                    map.put(key, group);
                }
            }
            
            List<List<String>> res = new ArrayList<List<String>>(map.values());
            
            return res;
            
        }
    }
    

Log in to reply
 

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