Leetcode 316.去除重复字母

去除重复字母

给定一个仅包含小写字母的字符串,去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

示例 1:

输入: "bcabc"

输出: "abc"

示例 2:

输入: "cbacdcbc"

输出: "acdb"

 

Given the string s, the greedy choice (i.e., the leftmost letter in the answer) is the smallest s[i], s.t. the suffix s[i .. ] contains all the unique letters. (Note that, when there are more than one smallest s[i]'s, we choose the leftmost one. Why? Simply consider the example: "abcacb".)

 

After determining the greedy choice s[i], we get a new string s' from s by

 

removing all letters to the left of s[i],

removing all s[i]'s from s.

 

We then recursively solve the problem w.r.t. s'.

 

The runtime is O(26 * n) = O(n).

 

 1 public class Solution{
 2     public String removeDuplicateLetters(String s){
 3         int[] cnt=new int[26];
 4         int pos=0;
 5         for(int i=0;i<s.length();i++) cnt[s.charAt(i)-'a']++;
 6         for(int i=0;i<s.length();i++){
 7             if(s.charAt(i)<s.charAt(pos)){
 8                 pos=i;
 9             }
10             if(--cnt[s.charAt(i)-'a']==0){
11                 break;
12             }
13         }
14         return s.length()==0?"":s.charAt(pos)+removeDuplicateLetters(s.substring(pos+1).replaceAll(""+s.charAt(pos),""));
15     }
16 }

 

posted on 2019-01-07 19:29  kexinxin  阅读(295)  评论(0编辑  收藏  举报

导航