1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class Solution { public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); for (int i = 0; i < strings.length; i++){ String temp = strings[i]; boolean found = false; for (int j = 0; j < result.size() && !found; j++){ found = isSameGroup(temp, result.get(j).get(0)); if (found){ result.get(j).add(temp); } } if (!found){ ArrayList<String> list = new ArrayList<String>(); list.add(temp); result.add(list); } } for (int i = 0; i < result.size(); i++) Collections.sort(result.get(i)); return result; } private boolean isSameGroup(String c, String d){ if (c.length() != d.length()) return false; if (c.length() == 0) return true; int difference = (c.charAt(0) - d.charAt(0)) %26; difference = difference < 0?difference+26:difference; for (int i = 1; i < c.length(); i++){ int localDiff = (c.charAt(i) - d.charAt(i)) %26; localDiff = localDiff < 0?localDiff+26:localDiff; if (localDiff != difference) return false; } return true; } } |
Friday, November 27, 2015
[leetcode] group Shifted Strings
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment