249.|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"]
,A solution is:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
一刷
题解:
就是问,哪些字符串属于同一个shift group.
首先,对于一个字符串,里面的每个字符减去第一个字符形成一个新的字符串。构成同一个新字符串的字符串属于同一个sequence
public class Solution {
public List groupStrings(String[] strings) {
List result = new ArrayList();
Map> map = new HashMap>();
for (String str : strings) {
int offset = str.charAt(0) - 'a';
StringBuilder key = new StringBuilder();
for (int i = 0;
i < str.length();
i++) {
char c = (char) (str.charAt(i) - offset);
if (c < 'a') {
c += 26;
}
key.append(c);
}
if (!map.containsKey(key.toString())) {
List list = new ArrayList();
map.put(key.toString(), list);
}
map.get(key.toString()).add(str);
}
for (String key : map.keySet()) {
List list = map.get(key);
result.add(list);
}
return result;
}
}
【249.|249. Group Shifted Strings】二刷
同上
public class Solution {
public List groupStrings(String[] strings) {
List res = new ArrayList<>();
Map> map = new HashMap<>();
for(String str : strings){
int offset = str.charAt(0) - 'a';
StringBuilder key = new StringBuilder();
for(int i=0;
i val = new ArrayList<>();
map.put(key.toString(), val);
}
map.get(key.toString()).add(str);
}
for (Map.Entry> entry : map.entrySet()){
res.add(entry.getValue());
}
return res;
}
}
推荐阅读
- 一日一词|一日一词 shift
- ExpandableListView|ExpandableListView 实现点击某个group的时候再去请求网络动态加载子视图中的数据
- 目标用户偏好指数Target|目标用户偏好指数Target Group Index分析
- English|Ant Group Dismisses Rumor of Withdrawal Failure on Alipay
- 【Netty】四、事件循环EventLoop与EventLoopGroup
- 面试突击62(group|面试突击62:group by 有哪些注意事项())
- vue|vue,首页优化
- maven仓库类型说明hosted/proxy/group
- 关于|关于 SAP UI5 参数 $$updateGroupId 前面两个 $ 符号的含义
- 关于|关于 SAP UI5 Context.prototype.delete 方法的输入参数 Group ID 的细节