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" */