当前位置:网站首页>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
边栏推荐
- Mongodb commonly used 28 query statements (forward)
- Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
- Fs4059c is a 5V input boost charging 12.6v1.2a. Inputting a small current to three lithium battery charging chips will not pull it dead. The temperature is 60 ° and 1000-1100ma is recommended
- R语言使用dplyr包的group_by函数和summarise函数基于分组变量计算目标变量的均值、标准差
- Can mortgage with housing exclude compulsory execution
- 安装Mysql
- Understand chisel language thoroughly 07. Chisel Foundation (IV) - bundle and VEC
- IP 实验室月复盘 · 第 5 期
- 华昊中天冲刺科创板:年亏2.8亿拟募资15亿 贝达药业是股东
- 【R语言数据科学】:交叉验证再回首
猜你喜欢
好博医疗冲刺科创板:年营收2.6亿 万永钢和沈智群为实控人
MySQL8版本免安装步骤教程
吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest
MySQL5免安装修改
[matlab] summary of conv, filter, conv2, Filter2 and imfilter convolution functions
MySQL之详解索引
数据仓库面试问题准备
软件测试之测试评估
2022 hoisting machinery command examination simulation 100 questions simulation examination platform operation
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
随机推荐
markdown 语法之字体标红
php 日志调试
如何游戏出海代运营、游戏出海代投
Mask wearing detection based on yolov1
吃透Chisel语言.06.Chisel基础(三)——寄存器和计数器
[antd step pit] antd form cooperates with input Form The height occupied by item is incorrect
【Antd】Antd 如何在 Form.Item 中有 Input.Gourp 时获取 Input.Gourp 的每一个 Input 的value
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
吃透Chisel语言.08.Chisel基础(五)——Wire、Reg和IO,以及如何理解Chisel生成硬件
Error in find command: paths must precede expression (turn)
游戏出海,全球化运营
Understand chisel language thoroughly 04. Chisel Foundation (I) - signal type and constant
392. Judgement subsequence
IP lab monthly resumption · issue 5
IP 实验室月复盘 · 第 5 期
Summary of recent days (non-technical article)
mac redis安装与使用,连接远程服务器 redis
2022游戏出海实用发行策略
[antd] how to set antd in form There is input in item Get input when gourp Value of each input of gourp
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test