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"]
]

Note: For the return value, each inner list's elements must follow the lexicographic order.

一个字符串可以通过偏移变成另一个字符串,比如 ‘abc’ –> ‘bcd’ (所有字母右移一位),把可通过偏移转换的字符串归为一组。给定一个 String 数组,返回分组结果。

解法:将每个字符串都转换成与字符串首字符ASCII码值差的字符串,比如:'abc'就转换成'012','bcd'转换成了'012',两个就是同组的偏移字符串。用Hashmap来统计,key就是转换后的数字字符串,value是所有可以转换成此key的字符串集合。

注意:这个差值可能是负的,说明后面的字符比前面的小,此时加上26。

Java:

class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> result = new ArrayList<List<String>>();
HashMap<String, ArrayList<String>> map
= new HashMap<String, ArrayList<String>>(); for(String s: strings){
char[] arr = s.toCharArray();
if(arr.length>0){
int diff = arr[0]-'a';
for(int i=0; i<arr.length; i++){
if(arr[i]-diff<'a'){
arr[i] = (char) (arr[i]-diff+26);
}else{
arr[i] = (char) (arr[i]-diff);
} }
} String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(s);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(s);
map.put(ns, al);
}
} for(Map.Entry<String, ArrayList<String>> entry: map.entrySet()){
Collections.sort(entry.getValue());
} result.addAll(map.values()); return result;
}
}

Python: Time: O(nlogn), Space: O(n)

import collections

class Solution:
# @param {string[]} strings
# @return {string[][]}
def groupStrings(self, strings):
groups = collections.defaultdict(list)
for s in strings: # Grouping.
groups[self.hashStr(s)].append(s) result = []
for key, val in groups.iteritems():
result.append(sorted(val)) return result def hashStr(self, s):
base = ord(s[0])
hashcode = ""
for i in xrange(len(s)):
if ord(s[i]) - base >= 0:
hashcode += unichr(ord('a') + ord(s[i]) - base)
else:
hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
return hashcode

C++:  

class Solution {
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
vector<vector<string> > res;
unordered_map<string, multiset<string>> m;
for (auto a : strings) {
string t = "";
for (char c : a) {
t += to_string((c + 26 - a[0]) % 26) + ",";
}
m[t].insert(a);
}
for (auto it = m.begin(); it != m.end(); ++it) {
res.push_back(vector<string>(it->second.begin(), it->second.end()));
}
return res;
}
};  

  

类似题目:

[LeetCode] 49. Group Anagrams 分组变位词 

[LeetCode] 300. Longest Increasing Subsequence 最长递增子序列

All LeetCode Questions List 题目汇总

[LeetCode] 249. Group Shifted Strings 分组偏移字符串的更多相关文章

  1. LeetCode 249. Group Shifted Strings (群组移位字符串)$

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  2. [LeetCode#249] Group Shifted Strings

    Problem: Given a string, we can "shift" each of its letter to its successive letter, for e ...

  3. 249. Group Shifted Strings把迁移后相同的字符串集合起来

    [抄题]: Given a string, we can "shift" each of its letter to its successive letter, for exam ...

  4. 249. Group Shifted Strings

    题目: Given a string, we can "shift" each of its letter to its successive letter, for exampl ...

  5. [Locked] Group Shifted Strings

    Group Shifted Strings Given a string, we can "shift" each of its letter to its successive ...

  6. [LeetCode] Group Shifted Strings 群组偏移字符串

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  7. [Swift]LeetCode249.群组偏移字符串 $ Group Shifted Strings

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  8. LeetCode – Group Shifted Strings

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  9. Group Shifted Strings -- LeetCode

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

随机推荐

  1. 逆向破解之160个CrackMe —— 007

    CrackMe —— 007 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...

  2. Relief 过滤式特征选择

    给定训练集{(x1,y1),(x2,y2).....(xm,ym)} ,对每个示例xi,Relief在xi的同类样本中寻找其最近邻xi,nh(猜中近邻),再从xi的异类样本中寻找其最近邻xi,nm(猜 ...

  3. SQLAlchemy的应用创建

    1.首先创建app文件夹 同django 创建app 一样 创建文件 在创建的views中写入两个蓝图函数为了操作数据库的增删改查 acc.py from flask import Blueprint ...

  4. springmvc接收List型参数长度

    springmvc默认接收list参数长度为256,过长则报越界异常,添加 @InitBinder public void initBinder(WebDataBinder binder) { // ...

  5. scala 中的匹配模式

    unapply 仅作匹配,不作其它输出.返回 Boolean 值 object UpperCase { def unapply(s: String): Boolean = s.toUpperCase ...

  6. 转:MySQL到底能支持多大的数据量?

    MySQL到底能支持多大的数据量? MySQL是中小型网站普遍使用的数据库之一,然而,很多人并不清楚MySQL到底能支持多大的数据量,再加上某些国内CMS厂商把数据承载量的责任推给它,导致很多不了解M ...

  7. PHP——数组根据某一键值合并

    前言 其实要实现很简单直接foreach,再根据PHP中数组的特性就可以轻松实现. 步骤 这是源数据的格式 $info = [ [ "gname" => "特别关心 ...

  8. S1_搭建分布式OpenStack集群_07 nova服务配置 (计算节点)

    一.服务安装(计算节点)安装软件:# yum install openstack-nova-compute -y 编辑/etc/nova/nova.conf文件并设置如下内容:# vim /etc/n ...

  9. Windbg命令的语法规则系列(三)

    五.源文件行语法 可以将源文件行号指定为MASM表达式的全部或部分.这些数字计算出与该源代码行对应的可执行代码的偏移量.不能使用源代码行作为C++表达式的一部分.必须用重音符(`)将源文件和行号表达式 ...

  10. 4-微信小程序开发(小程序默认页面函数说明)

    https://www.cnblogs.com/yangfengwu/p/11601299.html 源码下载链接: 或者 首先说一下,怎么让自己的一个项目更改名字成为一个新的项目 然后用软件导入项目 ...