249. Group Shifted Strings
https://www.geeksforgeeks.org/group-shifted-string/ Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. Example: Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Output: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] class Solution { public List<List<String>> groupStrings(String[] strings) { // build a hashmap , key is a string of char differene betweens nei chars // value is a list of string with the same key HashMap<String, List<String>> map = new HashMap(); for(String word : strings){ String key = helper(word); if(!map.containsKey(key)){ map.put(key, new ArrayList<>()); } map.get(key).add(word); } List<List<String>> res = new ArrayList<>(); for(String key : map.keySet()){ // keySet, not KeySet List<String> list = map.get(key); Collections.sort(list); res.add(list); } return res; } private String helper(String word){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < word.length() - 1; i++){ int first = word.charAt(i) - 'a'; int sec = word.charAt(i + 1) - 'a'; int diff = first - sec; if(diff < 0) diff += 26; sb.append(diff); } return sb.toString(); } }
posted on 2018-11-08 02:22 猪猪🐷 阅读(101) 评论(0) 收藏 举报
浙公网安备 33010602011771号