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"
1 public class Solution { 2 public string RemoveDuplicateLetters(string s) { 3 return RDL(s); 4 } 5 6 public string RDL(string s) { 7 if (s == "") return ""; 8 9 var dict = new Dictionary<char, int>(); 10 11 foreach (char c in s) 12 { 13 if (!dict.ContainsKey(c)) 14 { 15 dict[c] = 0; 16 } 17 18 dict[c]++; 19 } 20 21 int pos = 0; 22 23 for (int i = 0; i < s.Length; i++) 24 { 25 if ((int)s[i] < (int)s[pos]) 26 { 27 pos = i; 28 } 29 30 if (--dict[s[i]] == 0) 31 { 32 break; 33 } 34 } 35 36 return s[pos] + RDL(s.Substring(pos + 1, s.Length - pos - 1).Replace(s[pos].ToString(), "")); 37 } 38 }

浙公网安备 33010602011771号