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 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

Approach #1: C++. [brute froce]

class Solution {
public:
string removeDuplicateLetters(string s) {
int size = s.size();
if (size == 0) return ""; int l = 0;
string ret = ""; vector<int> cnt(26, 0);
for (int j = 0; j < size; ++j) {
cnt[s[j] - 'a'] = 1;
}
int total_diff = std::accumulate(cnt.begin(), cnt.end(), 0); for (int z = 0; z < total_diff; ++z) {
for (int i = 0; i < 26; ++i) {
int appear = -1;
for (int j = l; j < size; ++j) {
if (s[j] - 'a' == i && ret.find('a' + i) == -1) {
appear = j;
break;
}
}
if (appear == -1) continue; vector<int> cnt2(26, 0);
for (int j = appear; j < size; ++j)
cnt2[s[j] - 'a'] = 1;
for (auto c : ret)
cnt2[c - 'a'] = 1;
int num = std::accumulate(cnt2.begin(), cnt2.end(), 0);
if (num == total_diff) {
ret += char('a' + i);
l = appear + 1;
break;
}
}
} return ret;
}
};

  

Approach #2: C++.

class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> cand(256, 0);
vector<bool> visited(256, false); for (auto c : s)
cand[c]++; string ret = "0"; for (auto c : s) {
cand[c]--;
if (visited[c]) continue;
while (c < ret.back() && cand[ret.back()]) {
visited[ret.back()] = false;
ret.pop_back();
}
visited[c] = true;
ret += c;
} return ret.substr(1);
}
};

  

reference:

https://leetcode.com/problems/remove-duplicate-letters/discuss/76767/C%2B%2B-simple-solution-easy-understanding

http://www.cplusplus.com/reference/numeric/accumulate/

最新文章

  1. ABP框架 - 多租户
  2. vue学习
  3. MySQL Cursor
  4. jQuery回调、递延对象总结(上篇)—— jQuery.Callbacks
  5. Sql Server 孤立用户解决办法
  6. Linux中使用crontab命令定时执行shell脚本或其他Linux命令
  7. centos5.4下mysql主从复制
  8. Integer Inquiry_hdu_1047(大数).java
  9. hdu 5612 Baby Ming and Matrix games
  10. MySQL学习笔记(4) - 创建数据库
  11. 探究adroid活动
  12. HTTP的请求头标签If-Modified-Since
  13. Defender Game 游戏实践(1) 基本游戏场景实现
  14. 一天搞定CSS: CSS选择器优先级--08
  15. Hadoop的配置过程(虚拟机中的伪分布模式)
  16. Part 7:自定义admin站点--Django从入门到精通系列教程
  17. Linux常用命令(第二版) --系统开关机命令
  18. kodi18.1设置中文的方法
  19. glup简单应用---gulpfile.js
  20. SudaMod-81.0 / crDroidAndroid-8.1(android-8.1.0_r20)红米3 2018年5月3日更新

热门文章

  1. C#获取网络状态
  2. 本人编写的一份前端vue面试题
  3. java成神之——数值操作BigDecimal,BigInteger,Random,SecureRandom
  4. plsql中调试函数 转
  5. 转gif图
  6. LINUX的SSH下FTP到远程服务器Entering Passive Mode失败解决
  7. java中的报错机制
  8. Aws s3 api
  9. Unity3d平台信息设置
  10. 【转】在SharePoint Server 2010中更改&ldquo;我的网站&rdquo;