Leetcode Remove Duplicate Letters

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/remove-duplicate-letters/

Topic:

Given a string which contains only lowercase letters, remove duplicate letters so this every letter appear once and only O nCE. You must make sure your result are the smallest in lexicographical order among all possible results.

Example:

Given"bcabc"
Return"abc"

Given"cbacdcbc"
Return"acdb"

Exercises

After the character, find the smallest string that matches the order of the original string.

Count is counted first for the number of the original char. Returns the position of the first char of a string with a PO. If you encounter S.charat (i) < S.charat (PO), update the PO to I.

The number of S.charat (i) corresponding to count is also reduced. When the quantity is 0, the only char that has just been lost is indicated. A char on the PO is the first char to return.

Recursively substring the back of the PO.

Time Complexity:o (n^2). Recursive call. N + (n-1) + ... + 1. Space:o (n).

AC Java:

1  Public classSolution {2      Publicstring Removeduplicateletters (string s) {3         if(s = =NULL|| S.length () = = 0){4             returns;5         }6         int[] Count =New int[26];7         intLen =s.length ();8          for(inti = 0; i<len; i++){9Count[s.charat (i)-' a ']++;Ten         } One         intPO = 0; A          for(inti = 0; i<len; i++){ -             if(S.charat (i) <S.charat (PO)) { -PO =i; the             } -Count[s.charat (i)-' a ']--; -             if(Count[s.charat (i)-' a '] = = 0) {//a unique value is lost, and char on the PO is the first char that returns a string -                  Break;  +             } -         } +          AString first =string.valueof (S.charat (PO)); at         returnFirst + removeduplicateletters (s.substring (po+1) replaceall (First, "")); -     } -}

Leetcode Remove Duplicate Letters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.