[leetcode] remove duplicate letters

用時4ms,內存1M (好高啊魂淡數組

思路:spa

先找出在「仍保留原字符串中全部字母種類,開頭字母最小」的後綴子字符串。i.e.若是前面遍歷到的字母在後面仍有出現則忽略掉,繼續找最小首字母。code

實現爲:blog

//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操做」。內存

完整實現:rem

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);
    }
};
相關文章
相關標籤/搜索