249.Group Shifted Strings
Posted 我的名字叫周周
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了249.Group Shifted Strings相关的知识,希望对你有一定的参考价值。
/* *249.Group Shifted Strings *2016-6-18 by Mingyang *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. *For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], *Return: *[ * ["abc","bcd","xyz"], * ["az","ba"], * ["acef"], * ["a","z"] *] *这个题目一看就是HashMap,刚开始我说那String的长度来存作为key,但是发现相同长度的string可能不为同一阵营 *所以后面该用一个新的string,就是把每两个字符之间的差存起来,写出一个string *["eqdf", "qcpr"]。 *((‘q’ - ‘e‘) + 26) % 26 = 12, ((‘d’ - ‘q‘) + 26) % 26 = 13, ((‘f’ - ‘d‘) + 26) % 26 = 2 *((‘c’ - ‘q‘) + 26) % 26 = 12, ((‘p’ - ‘c‘) + 26) % 26 = 13, ((‘r’ - ‘p‘) + 26) % 26 = 2 *所以"eqdf"和"qcpr"是一组shifted strings。 */ public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); HashMap<String, List<String>> d = new HashMap<String, List<String>>(); for(int i = 0; i < strings.length; i++) { StringBuffer sb = new StringBuffer(); for(int j = 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 = new ArrayList<String>(); l.add(strings[i]); d.put(shift, l); } } for(String s : d.keySet()) { Collections.sort(d.get(s)); result.add(d.get(s)); } return result; }
以上是关于249.Group Shifted Strings的主要内容,如果未能解决你的问题,请参考以下文章
java 249. Group Shifted Strings.java
java 249. Group Shifted Strings.java
java 249. Group Shifted Strings.java
java 249. Group Shifted Strings.java