当前位置:网站首页>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
边栏推荐
- 吃透Chisel语言.08.Chisel基础(五)——Wire、Reg和IO,以及如何理解Chisel生成硬件
- 【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
- 2022危险化学品经营单位主要负责人练习题及模拟考试
- Dgraph: large scale dynamic graph dataset
- go vendor 项目迁移到 mod 项目
- 自主工业软件的创新与发展
- Error in find command: paths must precede expression (turn)
- Unittest框架中引入TestFixture
- 吃透Chisel语言.06.Chisel基础(三)——寄存器和计数器
- qt 怎么检测鼠标在不在某个控件上
猜你喜欢
国内酒店交易DDD应用与实践——代码篇
[antd step pit] antd form cooperates with input Form The height occupied by item is incorrect
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
安装Mysql
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
Understand chisel language thoroughly 09. Chisel project construction, operation and testing (I) -- build and run chisel project with SBT
Test evaluation of software testing
sharding key type not supported
MySQL5免安装修改
随机推荐
Worried about "cutting off gas", Germany is revising the energy security law
Gorm data insertion (transfer)
Read excel table data
Understand chisel language thoroughly 03. Write to the developer of Verilog to chisel (you can also see it without Verilog Foundation)
Unittest框架之断言
ARouter的使用
小程序直播 + 电商,想做新零售电商就用它吧!
【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
WS2818M是CPC8封装,是三通道LED驱动控制专用电路外置IC全彩双信号5V32灯可编程led灯带户外工程
The font of markdown grammar is marked in red
Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型(转)
海外游戏代投需要注意的
瑞吉外卖笔记
Yingshi Ruida rushes to the scientific and Technological Innovation Board: the annual revenue is 450million and the proposed fund-raising is 979million
392. Judgement subsequence
吃透Chisel语言.03.写给Verilog转Chisel的开发者(没有Verilog基础也可以看看)
JVM 内存布局详解,图文并茂,写得太好了!
【Antd踩坑】Antd Form 配合Input.Group时出现Form.Item所占据的高度不对
游戏出海,全球化运营
MySQL8版本免安装步骤教程