当前位置:网站首页>划分字母区间[贪心->空间换时间->数组hash优化]
划分字母区间[贪心->空间换时间->数组hash优化]
2022-08-11 01:16:00 【REN_林森】
前言
贪心是一个很考察分析能力的题型之一,第一步需要分析到贪心点,第二步需要利用已知数据结构来完成构建代码,当如果不能直接解决,那就要考虑是否需要问题转换一下了。
一、划分字母区间
二、贪心&hash数组
从左到到右,一旦右边没前面出现的字符,就切断。(贪心点)
如何实现?即如何知道右边还有没有该字符?从后往前先标记最后一个字符的位置。
package everyday.greed;
import java.util.*;
// 划分字母区间
public class PartitionLabels {
// 从左到到右,一旦右边没前面出现的字符,就切断。(贪心点)
// 如何实现?即如何知道右边还有没有该字符?从后往前先标记最后一个字符的位置。
public List<Integer> partitionLabels(String s) {
Map<Character, Integer> fx = new HashMap<>();
char[] arr = s.toCharArray();
for (int i = arr.length - 1; i >= 0; i--) if (!fx.containsKey(arr[i])) fx.put(arr[i], i);
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
size = fx.get(arr[i]);
for (int j = i + 1; j < size; j++) {
if (fx.get(arr[j]) > size) size = fx.get(arr[j]);
}
ans.add(size - i + 1);
i = size;
}
return ans;
}
int size;
// hash数组会更快。
public List<Integer> partitionLabels2(String s) {
int[] fx = new int[26];
char[] arr = s.toCharArray();
for (int i = arr.length - 1; i >= 0; i--) if (fx[arr[i] - 'a'] == 0) fx[arr[i] - 'a'] = i;
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
size = fx[arr[i] - 'a'];
for (int j = i + 1; j < size; j++) {
if (fx[arr[j] - 'a'] > size) size = fx[arr[j] - 'a'];
}
ans.add(size - i + 1);
i = size;
}
return ans;
}
}
总结
1)从分析贪心点,再到选者hashMap,再到hash优化,虽然没有问题转换,但是锻炼常规分析流程。
参考文献
[1] LeetCode 划分字母区间
边栏推荐
- 22/8/9 贪心问题合集
- How to convert url to obj or obj to url
- The concept of services
- 云原生-FRP内网穿透(详解)使用云服务器将内网集群服务暴露至公网(二)
- 导入数据包上传宝贝提示“类目不能为空”是什么原因,怎么解决?
- 数据分析面试手册《SQL篇》
- 深度解析volatile关键字(保证够全面)
- Sigma development pays attention to details
- C# using timer
- R language multiple linear regression, ARIMA analysis of the impact of different candidates in the United States on the economic GDP time series
猜你喜欢
容器技术真的是环境管理的救星吗?
[Server data recovery] Data recovery case of lvm information and VXFS file system corruption caused by raid5 crash
数据分析面试手册《统计篇》
Word set before the title page
J9数字论:DAO治理更像一种生态过程:治理原生于网络,不断演变
HW-蓝队工作流程(1)
Only lazy and hungry. You still don't understand the singleton pattern!
构建资源的弹性伸缩
二维数组实战项目--------《扫雷游戏》
Linux安装redis数据库
随机推荐
报考PMP需要做些什么准备?
[ASM] The relationship between the role of the bytecode operation ClassWriter COMPUTE_FRAMES and visitMaxs
【视频】报告分享|2021年保险行业数字化洞察
时间戳转换为日期格式、获取当前时间戳
还在用 Xshell?你 out 了,推荐一个更现代的终端连接工具,好用到爆!
Sub-database sub-table ShardingSphere-JDBC notes arrangement
如何做到构建的提速,再提速
MySQL进阶查询
22、库存服务
How to build speed, speed up again
EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object Pose Est...
Construction inspection, no rules and no square
微服务概念
【21天学习挑战赛】折半插入排序
Ambari Migrates Spark2 to Other Machines (Graphic and Text Tutorial)
力扣------值相等的最小索引
3d打印出现stl文件物体不是流形,意味着不是水密体...解决办法
Sigma development pays attention to details
【HFSS学习记录1】实例:宽带非对称多节定向耦合器设计
22. Inventory service