TopCoder problem "DyckwordUniformer" used in SRM 274 (Division I Level Two)



Problem Statement

    

A Dyck word is a string consisting of n X's and n Y's (for some positive integer n) such that no initial segment of the string has more Y's than X's.

If we have a Dyck word we can swap any two consecutive substrings when both of them are Dyck words. It is easy to show that the result of this swap operation is a Dyck word too. For example, in "XXYXXYYY" (quotes for clarity) we can swap the substrings "XY" and "XXYY" to get "XXXYYXYY".

If a Dyck word A can be obtained from a Dyck word B using some number of the described swap operations they are called equivalent.

You will be given a String dyckword. Return the lexicographically smallest (i.e., the one that occurs first in alphabetical order) Dyck word that is equivalent with the given dyckword. Return "" (the empty string) if the given string is not a Dyck word.

 

Definition

    
Class:DyckwordUniformer
Method:uniform
Parameters:String
Returns:String
Method signature:String uniform(String dyckword)
(be sure your method is public)
    
 

Constraints

-dyckword will contain between 2 and 50 characters, inclusive.
-Each character in dyckword will be either 'X' or 'Y'.
 

Examples

0)
    
"XXYXXYYY"
Returns: "XXXYYXYY"
The example from the problem statement.
1)
    
"XYXYXXXYYYXXYY"
Returns: "XXXYYYXXYYXYXY"
The result can be obtained by four swaps "XYXYXXXYYYXXYY" -> "XYXXXYYYXYXXYY" -> "XXXYYYXYXYXXYY" -> "XXXYYYXYXXYYXY" -> "XXXYYYXXYYXYXY".
2)
    
"XXXYYYXXYXXXYYYY"
Returns: "XXXXYYYXYYXXXYYY"
The result can be obtained by two swaps "XXXYYYXXYXXXYYYY" -> "XXXYYYXXXXYYYXYY" -> "XXXXYYYXYYXXXYYY".
3)
    
"XXYYYX"
Returns: ""

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=5887

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=8071&pm=5887

Writer:

Andrew_Lazarev

Testers:

PabloGilberto , brett1479 , Olexiy

Problem categories:

Brute Force, Recursion, Sorting