For example: "abc", "BCD". We can keep "shifting" which forms the sequence:"abc", "BCD", "XYZ"Given a list of string s 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"]
]
Note:for The return value, each inner list ' s elements must follow the lexicographic order.
Key point: Group all strings this belong to the same shifting sequence, so it is important to find the key that belongs to the same shift sequence. So the function shift is written separately,
Writing this shift function, I thought very complex, each string to move 26 distance, see shifted string is not a key. Why is it so complicated? Specifies a key of the same shift sequence, defined as the first char as ' a '
Buffer.append ((C-' a '-dist + +)% + ' a ') is extremely error-prone . It is important to establish the correct hashmap by storing the strings of the same shift sequence in the value corresponding to key.
1 Public classSolution {2 PublicList<list<string>>groupstrings (string[] strings) {3list<list<string>> res =NewArraylist<list<string>>();4 if(strings==NULL|| strings.length==0)returnRes;5hashmap<string, list<string>> map =NewHashmap<string, list<string>>();6 for(inti=0; i<strings.length; i++) {7String temp =shift (Strings[i]);8 if(Map.containskey (temp)) {9 Map.get (temp). Add (Strings[i]);Ten } One A Else { -List<string> li=NewArraylist<string>(); - Li.add (Strings[i]); the map.put (temp, li); - } - - } + for(list<string>each:map.values ()) { - Collections.sort (each); +Res.add (NewArraylist<string>(each)); A } at returnRes; - } - - Publicstring Shift (String cur) { -StringBuffer res =NewStringBuffer (); - intLen =cur.length (); in intDist = Cur.charat (0)-' a '; - for(intk=0; k<len; k++) { to //Res.append ((Cur.charat (k) +j> ' z ')? (' a ' + (int) (Cur.charat (k) +j-' z ')-1): (Cur.charat (k) +j)); + Charc =Cur.charat (k); -Res.append (c ' a '-dist+26)%26+ ' a '); the } * returnres.tostring (); $ }Panax Notoginseng}
Leetcode:group shifted Strings