[leetcode] remove duplicate letters
生活随笔
收集整理的這篇文章主要介紹了
[leetcode] remove duplicate letters
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用時4ms,內存1M (好高啊魂淡
思路:
先找出在“仍保留原字符串中所有字母種類,開頭字母最小”的后綴子字符串。i.e.如果前面遍歷到的字母在后面仍有出現則忽略掉,繼續找最小首字母。
實現為:
//counts數組存儲各類字母的數量 ,當某個字母減為0時說明后面不會再出現,應就此停止 for (int i=0;i<length;i++) {if (s[i]<smallest_ch) {smallest_ch_index=i;smallest_ch=s[i];}if(--counts[s[i]-'a']==0)break; }然后切掉可以省略的前半截字符串,答案應為“當前找到的最小首字母”+“首字母后的子串去掉所有該字母,再對該子串進行remove duplicate letters操作”。
完整實現:
class Solution { public:string removeDuplicateLetters(string s) {auto length=s.size();if (length<=1)return s;int counts[26]={0};for (int i=0;i<length;i++)++counts[s[i]-'a'];int smallest_ch_index=0;char smallest_ch=s[0];for (int i=0;i<length;i++) {if (s[i]<smallest_ch) {smallest_ch_index=i;smallest_ch=s[i];}if(--counts[s[i]-'a']==0)break;}string remained=s.substr(smallest_ch_index+1);while (remained.find(smallest_ch)!=string::npos)remained=remained.erase(remained.find(smallest_ch),1);return smallest_ch+removeDuplicateLetters(remained);} };?
轉載于:https://www.cnblogs.com/RDaneelOlivaw/p/10352326.html
總結
以上是生活随笔為你收集整理的[leetcode] remove duplicate letters的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows server 1709(
- 下一篇: Codeforces 1110 简要题解