• Remove Duplicate Letters


    316. Remove Duplicate Letters

    Total Accepted: 2367 Total Submissions: 12388 Difficulty: Medium

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

    Example:

    Given "bcabc"
    Return "abc"

    Given "cbacdcbc"
    Return "acdb"

    class Solution {
    public:
        string removeDuplicateLetters(string s) {
            int size = s.size();
            
            vector<int>  vec_cnts(26,0);
            
            for(int i=0; i<size ;++i){
                vec_cnts[s[i]-'a']++;
            }
            
            string res ;
            
            int res_ch_pos = -1;
            
            for(int i=0; i<size; ++i){
                if(vec_cnts[s[i]-'a'] == 0){
                    continue;    
                } 
                
                if(vec_cnts[s[i]-'a'] != 1) {
                    vec_cnts[s[i]-'a']--;
                    continue;
                }
        
                char ch     = s[i] ;
                int  ch_pos = i;
                int  j      = i-1;
            
                while(j  > res_ch_pos ){//从后往前找到最前边小于ch的字符,若是没找到小于的字符,则找最前边等于ch的字符
                    if(s[j] > ch  || vec_cnts[s[j]-'a'] == 0) {
                        --j; 
                        continue;
                    }
                    if(s[j] < ch){//小于
                        ch     = s[j];
                        ch_pos = j;
                    }else{//相等
                        ch_pos = j;    
                    }   
                    --j;
                }
                
                res.push_back(s[ch_pos]);//把找到的字符加入结果集
                
                vec_cnts[s[ch_pos]-'a'] = 0;//该字符已经使用,下次不能再使用了
                
                res_ch_pos = ch_pos;//更正当前结果中,最后一个字符所在的位置
                
                if(res_ch_pos < i){//如果结果字符在i之前,下次仍从i开始往前找
                    i -= 1;
                }
            }
    
            return res;
        }
    };
    /*
    "bbbacacca"
    
    */
  • 相关阅读:
    Python内置模块02
    Python常用模块
    hdu 5943(素数间隔+二分图匹配)
    poj 3372(找规律)
    poj 2369(置换群)
    poj 3270(置换群+贪心)
    bzoj 4034(DFS序+线段树)
    poj 2337(单向欧拉路的判断以及输出)
    poj 1041(字典序输出欧拉回路)
    csu 1798(树上最远点对,线段树+lca)
  • 原文地址:https://www.cnblogs.com/zengzy/p/5059695.html
Copyright © 2020-2023  润新知