[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 dijkstra 最短路算法示意代码
def dijkstra(graph, from_node, to_node): q, seen = [(0, from_node, [])], set() while q: cost, node, ...
- ThinkPHP模型中的HAS_ONE,BELONG_TO,HAS_MANY实践
因为很熟悉DJANGO,所以对TP,要慢慢适应. 1,SQL文件 /* Navicat MySQL Data Transfer Source Server : localhost_3306 Sourc ...
- python list 字符串排序
#coding:utf-8 import re s = ['dat2','dat10','dat5'] #方法一 new = sorted(s,key = lambda i:int(re.search ...
- 网站安全DDOS攻击及监测
一. 监测 在类Unix系统中可以使用top查看系统资源.进程.内存占用等信息.查看网络状态可以使用netstat.nmap等工具.若要查看实时的网络流量,监控TCP/IP连接等,则可以使用iftop ...
- linux命令 node常用
//查看进程netstat -nlp //查找某一进程 netstat -nlp | grep node //后台挂起 nohup npm start &
- laravel使用手札——使用PHPStorm提升开发速度
laravel使用手札——使用PHPStorm提升开发速度 phpstormphplaravel 阅读约 4 分钟 PHPStorm安装 PHPStorm 使用手札——安装看这里 代码自动提示支持 ...
- 数据库 Hash Join的定义,原理,算法,成本,模式和位图
Hash Join只能用于相等连接,且只能在CBO优化器模式下.相对于nested loop join,hash join更适合处理大型结果集 Hash Join的执行计划第1个是hash ...
- (尚024)Vue_案例_交互删除
注意:本总结中最终会删除不成功 ,原因是Item.vue中方法methods单词拼写错误!!! 首先明白,删除在Item.vue中交互 1.写交互,首先写监听@click="deleteIt ...
- learning java 使用WatchService监控文件变化
import java.io.IOException; import java.nio.file.*; public class WatchServiceTest { public static vo ...
- Windows加载器与模块初始化
本文是Matt Pietrek在1999年9月的MSJ杂志上发表的关于Windows加载器与模块初始化方面的文章.作者深入分析了LdrpRunInitialize璕outines例程的作用,用C语言写 ...