zoukankan      html  css  js  c++  java
  • Remove Duplicate Letters -- LeetCode

    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"

    思路:采用贪心算法,对于给定的字符串S,找到所有结果的最小前缀(即最小的字母),假如有多个最小前缀,则选择最左侧的。

    令最终选择的最小前缀的下标为pos,则删掉s[pos]左侧的所有字符,并删掉剩下字符串中所有与s[pos]相等的字符。

    C++中将某个特定字符从所有出现的位置删掉可以这样实现:

    s.erase(remove(s.begin(), s.end(), theCharacterNeedtoRemove), s.end());

    其中remove函数需要使用algorithm库文件。算法复杂度为O(26 * n) = O(n)

     1 class Solution {
     2 public:
     3     string removeDuplicateLetters(string s) {
     4         vector<int> alp(26, -1);
     5         for (int i = 0, n = s.size(); i < n; i++)
     6             alp[(int)(s[i] - 'a')] = i;
     7         int pos = -1;
     8         for (int i = 0, n = s.size(); i < n; i++)
     9         {
    10             int ind = (int)(s[i] - 'a');
    11             if (alp[ind] == -1) continue;
    12             if (pos == -1 || s[pos] > s[i]) pos = i;
    13             if (alp[ind] == i) break;
    14         }
    15         if (s == "" || pos == -1) return "";
    16         char cand = s[pos];
    17         s = s.substr(pos + 1);
    18         s.erase(remove(s.begin(), s.end(), cand), s.end());
    19         return cand + removeDuplicateLetters(s);
    20     }
    21 };
  • 相关阅读:
    lightoj-1047
    lightoj-1044
    lightoj-1045
    lightoj-1082
    LeetCode偶尔一题 —— 19. 删除链表的倒数第N个节点
    Python 3.52官方文档翻译 http://usyiyi.cn/translate/python_352/library/index.html 必看!
    Python3 time模块
    JavaScript CSS 等前端推荐
    Python之 七级字典查询
    将Sublime Text 3设置为Python全栈开发环境(转一个链接)
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5134881.html
Copyright © 2011-2022 走看看