简体   繁体   中英

Selecting next lexicographical shortest element

Jack and Daniel are friends. Both of them like letters, especially upper-case ones. They are cutting upper-case letters from newspapers, and each one of them has their collection of letters stored in separate stacks. One beautiful day, Morgan visited Jack and Daniel. He saw their collections. Morgan wondered what is the lexicographically minimal string, made of that two collections. He can take a letter from a collection when it is on the top of the stack. Also, Morgan wants to use all the letters in the boys' collections.

Input Format

The first line contains the number of test cases,t . Every next two lines have such format: the first line contains string a, and the second line contains string b.

Output the lexicographically minimal string for each test case in new line.

Sample Input

2

JACK

DANIEL

ABACABA

ABACABA

Sample Output

DAJACKNIEL

AABABACABACABA

Here is my approach:

t = int(raw_input())
for _ in range(t):
    a = raw_input()
    b = raw_input()
    i = 0
    j = 0
    prev = 0
    res = ""
    while i < len(a) and j < len(b):
        if a[i:] < b[j:]:
            res += a[i]
            i += 1
            prev = 0
        elif a[i:] > b[j:]:
            res += b[j]
            j += 1
            prev = 1
        else:
            if prev == 0:
                res += a[i]
                i += 1
                prev = 0
            else: 
                res += b[j]
                j += 1
                prev = 1
    print res + a[i:]+b[j:]

Consider the case when a = "C" and b = "CA" . Your program's output will be "CCA" but the right answer is "CAC" . The problem is that your code prefers "C" over "CA" because "C" < "CA" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM