当前位置:网站首页>Remove duplicate letters [greedy + monotonic stack (maintain monotonic sequence with array +len)]
Remove duplicate letters [greedy + monotonic stack (maintain monotonic sequence with array +len)]
2022-07-04 14:14:00 【REN_ Linsen】
greedy + Monotonic stack
Preface
When the design reaches the most word problem , Most of them involve greedy algorithms , This situation , Understand the process of greed by yourself , And then embodied in the code .
When it comes to relative order / Front and back size , Generally, we need to use monotone stack for maintenance , Common scenes : Back to back hedge .
For monotone stacks /hash And so on , Can use array , You can still use arrays , stay JVM level , Do than API The layer is much faster , And simple and lightweight .
One 、 Remove duplicate letters

Two 、 greedy + Monotonic stack
1、stack
// Take out the duplicate string
public class RemoveDuplicateLetters {
/* target: Remove duplicate letters , The lexicographic order of the returned result is the smallest . When s[i] >= s[i+1] And s[i] There are many cases , Then put s[i] Replace with ‘#’ Number , then s[i - 1] If any , And s[i+1] Compare . This feeling of going back , Truth is a monotonous stack of ideas . */
public String removeDuplicateLetters(String s) {
char[] arr = s.toCharArray();
// Record how many characters there are .
int[] fx = new int[26];
for (char c : arr) fx[c - 'a']++;
// duplicate removal .
Stack<Character> sk = new Stack<>();
int[] set = new int[26];
for (int i = 0; i < arr.length; i++) {
// Put the big one in front , And there are repeated characters after it , Just eliminate , Keep the front as monotonous as possible , Even if it's not monotonous , That character must be only 1 individual .
while (!sk.isEmpty() && sk.peek() > arr[i] && fx[sk.peek() - 'a'] != 1 && set[arr[i] - 'a'] == 0) {
System.out.println(fx[sk.peek() - 'a']);
--fx[sk.peek() - 'a'];
set[sk.pop() - 'a'] = 0;
}
// Add new characters , If the new character has been added before , Don't add this , After all, try to put the same small characters in front of the smallest .
if (set[arr[i] - 'a'] == 0) {
// There is no , And it is relatively monotonous with the characters in the monotone stack .
sk.push(arr[i]);
// Set that it already exists in the monotone stack .
set[arr[i] - 'a'] = 1;
} else --fx[arr[i] - 'a'];// Characters to be removed , So the number needs to be reduced 1
}
// Combine relatively monotonous characters into monotonic strings .
StringBuilder sb = new StringBuilder();
while (!sk.isEmpty()) sb.insert(0, sk.pop());
return sb.toString();
}
public static void main(String[] args) {
new RemoveDuplicateLetters().removeDuplicateLetters("abafdsfasfasdfasdfasdfasfsdagewha");
}
}
2、 Native array +len replace stack
// Try it out , Replace stack with array .
// Sure enough , Native arrays are really fast .
class RemoveDuplicateLetters2 {
/* target: Remove duplicate letters , The lexicographic order of the returned result is the smallest . When s[i] >= s[i+1] And s[i] There are many cases , Then put s[i] Replace with ‘#’ Number , then s[i - 1] If any , And s[i+1] Compare . This feeling of going back , Truth is a monotonous stack of ideas . */
public String removeDuplicateLetters(String s) {
char[] arr = s.toCharArray();
// Record how many characters there are .
int[] fx = new int[26];
for (char c : arr) fx[c - 'a']++;
// duplicate removal .
char[] sk = new char[s.length()];
int skLen = 0;
int[] set = new int[26];
for (int i = 0; i < arr.length; i++) {
// Put the big one in front , And there are repeated characters after it , Just eliminate , Keep the front as monotonous as possible , Even if it's not monotonous , That character must be only 1 individual .
while (skLen != 0 && sk[skLen - 1] > arr[i] && fx[sk[skLen - 1] - 'a'] != 1 && set[arr[i] - 'a'] == 0) {
System.out.println(fx[sk[skLen - 1] - 'a']);
--fx[sk[skLen - 1] - 'a'];
set[sk[--skLen] - 'a'] = 0;
}
// Add new characters , If the new character has been added before , Don't add this , After all, try to put the same small characters in front of the smallest .
if (set[arr[i] - 'a'] == 0) {
// There is no , And it is relatively monotonous with the characters in the monotone stack .
sk[skLen++] = arr[i];
// Set that it already exists in the monotone stack .
set[arr[i] - 'a'] = 1;
} else --fx[arr[i] - 'a'];// Characters to be removed , So the number needs to be reduced 1
}
// Combine relatively monotonous characters into monotonic strings .
StringBuilder sb = new StringBuilder();
while (skLen != 0) sb.insert(0, sk[--skLen]);
return sb.toString();
}
}
summary
1) Involve the most words , Lenovo is greedy for knowledge ; Involving order / Front and back size classes , Lenovo monotone stack knowledge points .
2) Array hash/ Array simulation stack , Compared with HashMap/Stack class , Much faster , Just as native heap sorting is faster than priority queues .
reference
边栏推荐
- Deming Lee listed on Shenzhen Stock Exchange: the market value is 3.1 billion, which is the husband and wife of Li Hu and Tian Hua
- R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)
- Mongodb commonly used 28 query statements (forward)
- Excel快速合并多行数据
- IP 实验室月复盘 · 第 5 期
- C# wpf 实现截屏框实时截屏功能
- Interview disassembly: how to check the soaring usage of CPU after the system goes online?
- Common content type correspondence table
- go语言中的文件创建,写入,读取,删除(转)
- Unity Shader学习(三)试着绘制一个圆
猜你喜欢

Unittest中的TestSuite和TestRunner

国内酒店交易DDD应用与实践——代码篇

【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法

Unity Shader学习(三)试着绘制一个圆

华昊中天冲刺科创板:年亏2.8亿拟募资15亿 贝达药业是股东

锐成芯微冲刺科创板:年营收3.67亿拟募资13亿 大唐电信是股东

2022危险化学品经营单位主要负责人练习题及模拟考试

英视睿达冲刺科创板:年营收4.5亿 拟募资9.79亿

2022 hoisting machinery command examination simulation 100 questions simulation examination platform operation

Huahao Zhongtian sprint Technology Innovation Board: perte annuelle de 280 millions de RMB, projet de collecte de fonds de 1,5 milliard de Beida Pharmaceutical est actionnaire
随机推荐
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
奇妙秘境 码蹄集
数据仓库面试问题准备
gorm 之数据插入(转)
【C 题集】of Ⅶ
【Antd踩坑】Antd Form 配合Input.Group时出现Form.Item所占据的高度不对
File creation, writing, reading, deletion (transfer) in go language
ARouter的使用
How to choose a technology stack for web applications in 2022
Secretary of Homeland Security of the United States: domestic violent extremism is one of the biggest terrorist threats facing the United States at present
2022危险化学品经营单位主要负责人练习题及模拟考试
Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型(转)
Unittest框架之断言
C# wpf 实现截屏框实时截屏功能
小程序直播 + 电商,想做新零售电商就用它吧!
华昊中天冲刺科创板:年亏2.8亿拟募资15亿 贝达药业是股东
去除重复字母[贪心+单调栈(用数组+len来维持单调序列)]
Migration from go vendor project to mod project
富文本编辑:wangEditor使用教程
Product identification of intelligent retail cabinet based on paddlex