/* *249.group shifted Strings *2016-6-18 by Mingyang *given A string, we can "shift" all of 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. *for example, given: ["abc", "BCD", "ACEF", "XYZ", "AZ", "ba", "a", "Z"], *return: *[* ["abc", "BCD", "XYZ"] , * ["AZ", "BA"], * ["ACEF"], * ["a", "Z"] *] * This topic is hashmap, at first I said that the length of the string to save as key, but found the same length of Str ING may not be the same camp * So the next one is to use a new string, which is to save the difference between each two characters, write a string *["Eqdf", "QCPR"]. * ((' Q '-' e ') + +)% = 26, ((' d '-' Q ') + +)% =, ((' F '-' d ') + +)% = 2 * ((' C '-' Q ') + 26)% = 12 , ((' P '-' C ') + +)% =, ((' R '-' p ') + 26)% 26 = 2 * so "EQDF" and "QCPR" are a set of shifted strings.*/ PublicList<list<string>>groupstrings (string[] strings) {List<List<String>> result =NewArraylist<list<string>>(); HashMap<string, list<string>> d =NewHashmap<string, list<string>>(); for(inti = 0; i < strings.length; i++) {StringBuffer sb=NewStringBuffer (); for(intj = 0; J < Strings[i].length (); J + +) {Sb.append (Integer.tostring ((Strings[i].charat (j)-Strings[i].charat (0)) + 26)% 26)); Sb.append (" "); } String Shift=sb.tostring (); if(D.containskey (Shift)) {D.get (Shift). Add (Strings[i]); } Else{List<String> L =NewArraylist<string>(); L.add (Strings[i]); D.put (SHIFT, L); } } for(String s:d.keyset ()) {Collections.sort (D.get (s)); Result.add (D.get (s)); } returnresult; }
249.Group shifted Strings