Monday, August 7, 2017

[Leetcode] Remove Duplicate Letters, Solution

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"

[Thoughts]
首先统计每个字符出现的次数,然后重新扫描数组,保证每个字符在新字符串中只出现一次。


[Code]
1:    string removeDuplicateLetters(string s) {  
2:      vector<int> count(26, 0);  
3:      vector<int> visited(26, 0);  
4:        
5:      for(char c : s) {  
6:        count[c-'a']++;  
7:      }  
8:      string result= "";  
9:      for(char c : s) {  
10:        if(visited[c-'a'] == 1) {  
11:          count[c-'a']--;  
12:          continue;  
13:        }  
14:        while(result.size() > 0 && c < result.back() && count[result.back()-'a'] >0) {  
15:          visited[result.back()-'a'] = 0;  
16:          result.pop_back();  
17:        }  
18:        result += c;  
19:        visited[c-'a'] = 1;  
20:        count[c-'a']--;  
21:      }  
22:        
23:      return result;   
24:    }  

No comments: