My code:
public class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> ret = new ArrayList<List<String>>();
if (strings == null || strings.length == 0) {
return ret;
}
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for (int i = 0; i < strings.length; i++) {
String s = strings[i];
int offset = s.charAt(0) - 'a';
StringBuilder sb = new StringBuilder();
for (int j = 0; j < s.length(); j++) {
char c = (char) (s.charAt(j) - offset);
if (c < 'a') {
c = (char) (c + 26);
}
sb.append(c);
}
String shiftedStr = sb.toString();
if (!map.containsKey(shiftedStr)) {
map.put(shiftedStr, new ArrayList<String>());
}
map.get(shiftedStr).add(s);
}
for (String head : map.keySet()) {
ret.add(map.get(head));
}
return ret;
}
}
reference:
https://discuss.leetcode.com/topic/20722/my-concise-java-solution
这道题目也是没做出来。现在想想,思路还是很清晰的。
就是把所有的string全部转换到 ‘a’开头,然后hashtable 解决。
好久没做string,有些生疏。
Anyway, Good luck, Richardo! — 09/18/2016