[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);
    }
};

 

posted @ 2019-02-04 22:48  丹尼尔奥利瓦  阅读(250)  评论(0编辑  收藏  举报