原题链接在这里:https://leetcode.com/problems/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"
题解:
去重后,找到符合原来string中character先后顺序的最小string.
先用count来计数原来的每个char的数量。用po表示返回string的第一个char所在位置. 若是遇到s.charAt(i) < s.charAt(po)时,更新po到i.
count 对应的s.charAt(i)数量也要减小. 当数量为0时说明刚减掉了唯一的一个char. 此时说明在po上的char就是要返回的第一个char.
递归po后面的substring.
Time Complexity: O(n^2). 递归调用.n + (n-1) + ... + 1. Space: O(n).
AC Java:
1 public class Solution { 2 public String removeDuplicateLetters(String s) { 3 if(s == null || s.length() == 0){ 4 return s; 5 } 6 int [] count = new int[26]; 7 int len = s.length(); 8 for(int i = 0; i<len; i++){ 9 count[s.charAt(i) - ‘a‘]++; 10 } 11 int po = 0; 12 for(int i = 0; i<len; i++){ 13 if(s.charAt(i) < s.charAt(po)){ 14 po = i; 15 } 16 count[s.charAt(i) - ‘a‘]--; 17 if(count[s.charAt(i) - ‘a‘] == 0){ //减掉了一个唯一值,此时在po上的char就是返回string的第一个char 18 break; 19 } 20 } 21 22 String first = String.valueOf(s.charAt(po)); 23 return first + removeDuplicateLetters(s.substring(po+1).replaceAll(first, "")); 24 } 25 }
LeetCode Remove Duplicate Letters
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5241651.html