[LeetCode] 249. Group Shifted Strings 分组偏移字符串
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 分组偏移字符串的更多相关文章
- LeetCode 249. Group Shifted Strings (群组移位字符串)$
Given a string, we can "shift" each of its letter to its successive letter, for example: & ...
- [LeetCode#249] Group Shifted Strings
Problem: Given a string, we can "shift" each of its letter to its successive letter, for e ...
- 249. Group Shifted Strings把迁移后相同的字符串集合起来
[抄题]: Given a string, we can "shift" each of its letter to its successive letter, for exam ...
- 249. Group Shifted Strings
题目: Given a string, we can "shift" each of its letter to its successive letter, for exampl ...
- [Locked] Group Shifted Strings
Group Shifted Strings Given a string, we can "shift" each of its letter to its successive ...
- [LeetCode] Group Shifted Strings 群组偏移字符串
Given a string, we can "shift" each of its letter to its successive letter, for example: & ...
- [Swift]LeetCode249.群组偏移字符串 $ Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: & ...
- LeetCode – Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: & ...
- Group Shifted Strings -- LeetCode
Given a string, we can "shift" each of its letter to its successive letter, for example: & ...
随机推荐
- python爬虫中的ip代理设置
设置ip代理是爬虫必不可少的技巧: 查看本机ip地址:打开百度,输入“ip地址”,可以看到本机的IP地址: 本文使用的是goubanjia.com里面的免费ip: 使用时注意要注意传输协议是http还 ...
- JMeter+Maven+CSV数据驱动
1.整个工程的目录结构: 2.工程说明: # ddcapitest XXX_API自动化测试 # 一.文件说明: 1. ddcapitest/src/是工程的入口 ddcapitest/pom.xml ...
- janusgraph-控制台操作命令
当顶点数量过多时(我的230w)删除太慢 就用下面的命令, 删除整个图库 graph.close() JanusGraphFactory.drop(graph) 查询所有的顶点属性 用traversa ...
- L1219
八皇后问题. 然而重点在于判断斜线attack问题和 剪枝问题, 不过判断斜线这些东西都挺有意思的. 是坐标的思想但是 有不一样, 因为这个棋盘.. 斜线判断是可以理解了. 但是我想知道的是这个的原理 ...
- navicat设置唯一
https://blog.csdn.net/Song_JiangTao/article/details/82192189
- JavaScript开发——文件夹的上传和下载
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- 使用for循环签到嵌套制作直角三角形
注意代码的运行顺序: for(i = 0 ; i<9 ; i++){ for(j = 0 ; j<i-1 ; j++){ document.write("*")//** ...
- Lightning Web Components 开发指南(二)
Lightning Web Components 是自定义元素使用html 以及现代javascript进行构建. Lightning Web Components UI 框架使用web compon ...
- Log4net 数据库存储(四)
1.新建一个空的ASP.Net 空项目,然后添加Default.aspx窗体 2.添加配置文件:log4net.config <?xml version="1.0" enco ...
- 二八法则(The 80/20 Principle)
二八法则的定义:在任何一组事物中,最重要的只占其中一小部分,约20%,其余80%尽管占多数,却是次要的. 二八法则的例子:社会上20%的人占有80%的社会财富 20%的工厂有80%的产出 80%的利润 ...