• [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);
        }
    };
  • 相关阅读:
    Python-24-多线程
    RT-Thread动态内存堆的使用
    Linux编程概念
    Linux_C语言基础
    文件IO_open(),read(),write(),lseek(),close()
    SourceTree跳转注册的方法
    Linux——软件安装
    初学DOM树解析xml文件
    简单json语句转化为map保存
    最大独立集求解
  • 原文地址:https://www.cnblogs.com/RDaneelOlivaw/p/10352326.html
Copyright © 2020-2023  润新知