简体   繁体   English

选择下一个字典序最短的元素

[英]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. Morgan 想知道由这两个集合组成的按字典顺序排列的最小字符串是什么。 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 .第一行包含测试用例的数量,t。 Every next two lines have such format: the first line contains string a, and the second line contains string b.接下来的每两行都有这样的格式:第一行包含字符串 a,第二行包含字符串 b。

Output the lexicographically minimal string for each test case in new line.在新行中为每个测试用例输出字典序最小的字符串。

Sample Input样本输入

2 2

JACK杰克

DANIEL丹尼尔

ABACABA ABACABA

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" .考虑a = "C"b = "CA" Your program's output will be "CCA" but the right answer is "CAC" .您程序的输出将是"CCA"但正确的答案是"CAC" The problem is that your code prefers "C" over "CA" because "C" < "CA" .问题是你的代码更喜欢"C"不是"CA"因为"C" < "CA"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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