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"]
A solution is:

[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]

题目标签:Hash Table

  题目给了我们一个 strings array,让我们把不同移位距离的string 分开归类。

  首先来看一下相同移位距离string 的特性:

    相同的移位string,拥有相同的移位距离,比如abc, bcd, xyz 都是移位了1个距离。根据这个特性,我们可以把bcd 和 xyz 恢复到 abc。

  利用HashMap,把最原始的 归位string 当作key,把可以恢复到 原始的 归位string 的 所有strings(List)当作value 存入map。

  

Java Solution:

Runtime beats 44.74%

完成日期:11/04/2017

关键词:HashMap

关键点:利用 char - 'a' 把所有相同移位距离的strings 转换成 同一个原始string 存入map

 class Solution
{
public List<List<String>> groupStrings(String[] strings)
{
List<List<String>> res = new ArrayList<>(); HashMap<String, List<String>> map = new HashMap<>(); // store original string as key; (List) strings come from same original one as value
for(String str: strings)
{
int offset = str.charAt(0) - 'a';
String key = ""; for(int i=0; i<str.length(); i++)
{
char c = (char) (str.charAt(i) - offset);
if(c < 'a')
c += 26; key += c;
} if(!map.containsKey(key))
map.put(key, new ArrayList<String>()); map.get(key).add(str); } // add each key's value into res
for(String key: map.keySet())
{
res.add(map.get(key));
} return res;
}
}

参考资料:

https://discuss.leetcode.com/topic/20722/my-concise-java-solution

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

最新文章

  1. js中的constructor
  2. asp.net-枚举绑定控件
  3. Font Awesome图标库
  4. hdu3555 数位dp
  5. Hadoop执行作业时报错:java.lang.OutOfMemoryError: Java heap space
  6. 1,SFDC 管理员篇 - 基本设置
  7. javascript笔记——工作笔记
  8. JavaEE基本了解
  9. ASP连接MYSQL数据库
  10. linux登录windows服务器
  11. ios导航栏又按钮添加图片后使其保持原色
  12. MFC 中线程传递CString 是不安全的 转
  13. windows下安装php reids扩展
  14. shell中的数据生命周期scope
  15. (转)HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别
  16. 点击倒计时60S获取验证码
  17. npm init 命令生成package.json文件
  18. weblogic11g 修改密码和重置密码【原】
  19. jquery 动画总结(主要指效果函数)
  20. uip.h 笔记

热门文章

  1. vux+vuex+vue+Es6开发微信公众号的坑
  2. docker常用命令理解
  3. 代码分析工具splint安装介绍
  4. 「 RQNOJ PID204 」 特种部队
  5. Window下的———TOMCAT环境的配置
  6. TestNG参数化测试
  7. Hadoop Mapreduce 中的Partitioner
  8. Linux学习笔记记录(四)
  9. CCF201609-2 火车购票 java(100分)
  10. SecureCRT 8.0设置与使用