当前位置:网站首页>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
边栏推荐
- [FAQ] Huawei Account Service Error Report 907135701 Common reasons Summary and Solutions
- 奇妙秘境 码蹄集
- Understand chisel language thoroughly 05. Chisel Foundation (II) -- combinational circuits and operators
- IP lab monthly resumption · issue 5
- Common content type correspondence table
- MySQL version 8 installation Free Tutorial
- 小程序直播 + 电商,想做新零售电商就用它吧!
- Product identification of intelligent retail cabinet based on paddlex
- Unity Shader学习(三)试着绘制一个圆
- 吃透Chisel语言.06.Chisel基础(三)——寄存器和计数器
猜你喜欢
30: Chapter 3: develop Passport Service: 13: develop [change / improve user information, interface]; (use * * * Bo class to accept parameters, and use parameter verification)
JVM 内存布局详解,图文并茂,写得太好了!
Install MySQL
锐成芯微冲刺科创板:年营收3.67亿拟募资13亿 大唐电信是股东
去除重复字母[贪心+单调栈(用数组+len来维持单调序列)]
【R语言数据科学】:交叉验证再回首
中邮科技冲刺科创板:年营收20.58亿 邮政集团是大股东
Summary of recent days (non-technical article)
华昊中天冲刺科创板:年亏2.8亿拟募资15亿 贝达药业是股东
吃透Chisel语言.05.Chisel基础(二)——组合电路与运算符
随机推荐
2022危险化学品经营单位主要负责人练习题及模拟考试
去除重复字母[贪心+单调栈(用数组+len来维持单调序列)]
Hardware Basics - diode Basics
IP 实验室月复盘 · 第 5 期
392. 判断子序列
sharding key type not supported
Interview disassembly: how to check the soaring usage of CPU after the system goes online?
Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
Detailed explanation of Fisher information quantity detection countermeasure sample code
递增的三元子序列[贪心训练]
吃透Chisel语言.10.Chisel项目构建、运行和测试(二)——Chisel中生成Verilog代码&Chisel开发流程
Product identification of intelligent retail cabinet based on paddlex
学习项目是自己找的,成长机会是自己创造的
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
markdown 语法之字体标红
2022游戏出海实用发行策略
golang fmt.printf()(转)
golang fmt. Printf() (turn)
MongoDB常用28条查询语句(转)
程序员的焦虑