当前位置:网站首页>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
边栏推荐
- 苹果5G芯片研发失败:继续依赖高通,还要担心被起诉?
- Qt如何实现打包,实现EXE分享
- 【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
- 程序员的焦虑
- Gorm read / write separation (rotation)
- R语言使用dplyr包的mutate函数对指定数据列进行标准化处理(使用mean函数和sd函数)并基于分组变量计算标准化后的目标变量的分组均值
- R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)
- Worried about "cutting off gas", Germany is revising the energy security law
- FS4059C是5V输入升压充电12.6V1.2A给三节锂电池充电芯片 输入小电流不会拉死,温度60°建议1000-1100MA
- 德明利深交所上市:市值31亿 为李虎与田华夫妻档
猜你喜欢

【FAQ】華為帳號服務報錯 907135701的常見原因總結和解决方法

Understand chisel language thoroughly 05. Chisel Foundation (II) -- combinational circuits and operators

吃透Chisel语言.05.Chisel基础(二)——组合电路与运算符

392. 判断子序列

吃透Chisel语言.09.Chisel项目构建、运行和测试(一)——用sbt构建Chisel项目并运行

好博医疗冲刺科创板:年营收2.6亿 万永钢和沈智群为实控人

苹果5G芯片研发失败:继续依赖高通,还要担心被起诉?
![30: Chapter 3: develop Passport Service: 13: develop [change / improve user information, interface]; (use * * * Bo class to accept parameters, and use parameter verification)](/img/89/aabf79ca02bf587e93885cadd5f98a.png)
30: Chapter 3: develop Passport Service: 13: develop [change / improve user information, interface]; (use * * * Bo class to accept parameters, and use parameter verification)

吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest

吃透Chisel语言.10.Chisel项目构建、运行和测试(二)——Chisel中生成Verilog代码&Chisel开发流程
随机推荐
苹果5G芯片研发失败:继续依赖高通,还要担心被起诉?
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
Understand chisel language thoroughly 04. Chisel Foundation (I) - signal type and constant
Error in find command: paths must precede expression (turn)
Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
Yingshi Ruida rushes to the scientific and Technological Innovation Board: the annual revenue is 450million and the proposed fund-raising is 979million
Apple 5g chip research and development failure: continue to rely on Qualcomm, but also worry about being prosecuted?
2022 practice questions and mock exams for the main principals of hazardous chemical business units
【FAQ】華為帳號服務報錯 907135701的常見原因總結和解决方法
Assertion of unittest framework
基于PaddleX的智能零售柜商品识别
FS4059C是5V输入升压充电12.6V1.2A给三节锂电池充电芯片 输入小电流不会拉死,温度60°建议1000-1100MA
吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest
Understand chisel language thoroughly 08. Chisel Foundation (V) -- wire, REG and IO, and how to understand chisel generation hardware
GCC【6】- 编译的4个阶段
Understand chisel language thoroughly 07. Chisel Foundation (IV) - bundle and VEC
好博医疗冲刺科创板:年营收2.6亿 万永钢和沈智群为实控人
Excel快速合并多行数据
30: Chapter 3: develop Passport Service: 13: develop [change / improve user information, interface]; (use * * * Bo class to accept parameters, and use parameter verification)
[R language data science]: cross validation and looking back