LeetCode 316. Remove Duplicate Letters

题意:

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"

思路:

这道题想了好久, 没有想出太好的方法。

正解是。 先统计每个字母的次数, 从头遍历字符串, 遍历的时候每到一个位置 统计值相应的减一。 当有一个减到0时,这说明有一个char能确定了。确定的就是出现过的字典序最小的那个。 找到之后,递归处理剩下的。

AC代码:

class Solution {
public:
    string removeDuplicateLetters(string s) {
       if(s == "") return "";
       int cnt[26] = {0};
       for(int i=0; i<s.length(); i++)
       {
           cnt[ s[i]-'a' ] ++;
       }
       int pos = 0;
       for(int i=0; i<s.length(); i++)
       {
           if(s[i] < s[pos])
           {
               pos = i;
           }
           cnt[ s[i] -'a' ]--;
           if( cnt[ s[i]-'a' ] == 0 )
                break;
       }
       string Left="";
       for(int i=pos+1; i<s.length(); i++)
       {
           if(s[i] != s[pos])
           Left += s[i];
       }
       string ret = "";
       ret += s[pos];
       
       return ret + removeDuplicateLetters( Left  );
    }
};

 

posted @ 2016-03-31 23:12  Gu Feiyang  阅读(109)  评论(0)    收藏  举报