首页 > 试题广场 >

字符串合并处理

[编程题]字符串合并处理
  • 热度指数:221816 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给定的由大小写字母和数字构成的字符串 st,记下标从 1 开始。按以下两个阶段进行处理:

\hspace{15pt}【合并阶段】
\hspace{23pt}\bullet\,第一步,将 st 合并,形成一个新字符串 u
\hspace{23pt}\bullet\,第二步,将 u 中奇数位字符按 Ascii 码从小到大(\texttt{`A'} \lt \texttt{`B'} \cdots \lt \texttt{`Z'} \lt \texttt{`a'} \lt \cdots \lt \texttt{`z'})进行排序,随后将偶数位字符也按 Ascii 码从小到大进行排序,得到 u'

\hspace{15pt}【调整阶段】
\hspace{15pt}随后,从左到右遍历 u' 中的每一个字符 u'_i
\hspace{23pt}\bullet\,第一步,若 u'_i 不是合法十六进制字符(即不为 \texttt{0-9}\texttt{a-f}\texttt{A-F}),则保留原字符,直接追加到结果中;否则,将其转换为十进制数。
\hspace{23pt}\bullet\,第二步,将该十进制数转换为四位二进制数(高位不足补 0,例如 (5)_{10}=(\texttt{0101})_2);
\hspace{23pt}\bullet\,第三步,将该二进制数翻转(反过来书写);
\hspace{23pt}\bullet\,第四步,将该二进制数转换为大写的十六进制数,追加到结果中。

\hspace{15pt}最终输出上述拼接而成的字符串。

输入描述:
\hspace{15pt}在一行上输入两个长度 1 \leqq {\rm length}(s), {\rm length}(t) \leqq 100,由大小写字母和数字构成的字符串 st,代表待处理的字符串。


输出描述:
\hspace{15pt}输出处理后的最终字符串。
示例1

输入

dec fab

输出

5D37BF

说明

\hspace{15pt}在这个样例中,全过程描述如下:
\hspace{15pt}【合并阶段】
\hspace{23pt}\bullet\,第一步合并得到 u = \texttt{
\hspace{23pt}\bullet\,第二步排序得到 u' = \texttt{
\hspace{15pt}【调整阶段】
\hspace{23pt}\bullet\,对于第一个字符 (\texttt{a})_{16},其十进制数为 (10)_{10},二进制数为 (\texttt{1010})_2,翻转后得到 (\texttt{0101})_2,再转换回十六进制数为 (\texttt{5})_{16}
\hspace{23pt}\bullet\,第二个字符 (\texttt{b})_{16}=(11)_{10}=(\texttt{1011})_2,翻转 (\texttt{1101})_2=(\texttt{D})_{16}
\hspace{23pt}\bullet\,第三个字符 (\texttt{c})_{16}=(12)_{10}=(\texttt{1100})_2,翻转 (\texttt{0011})_2=(\texttt{3})_{16}
\hspace{23pt}\bullet\,第四个字符 (\texttt{e})_{16}=(14)_{10}=(\texttt{1110})_2,翻转 (\texttt{0111})_2=(\texttt{7})_{16}
\hspace{23pt}\bullet\,第五个字符 (\texttt{d})_{16}=(13)_{10}=(\texttt{1101})_2,翻转 (\texttt{1011})_2=(\texttt{B})_{16}
\hspace{23pt}\bullet\,第六个字符 (\texttt{f})_{16}=(15)_{10}=(\texttt{1111})_2,翻转 (\texttt{1111})_2=(\texttt{F})_{16}
示例2

输入

abV CDw

输出

B3VD5w

说明

\hspace{15pt}在这个样例中,全过程描述如下:
\hspace{15pt}【合并阶段】
\hspace{23pt}\bullet\,第一步合并得到 u = \texttt{
\hspace{23pt}\bullet\,第二步排序得到 u' = \texttt{
\hspace{15pt}【调整阶段】
\hspace{23pt}\bullet\,对于第一个字符 (\texttt{D})_{16},其十进制数为 (13)_{10},二进制数为 (\texttt{1101})_2,翻转后得到 (\texttt{1011})_2=(\texttt{B})_{16}
\hspace{23pt}\bullet\,第二个字符 (\texttt{C})_{16}=(12)_{10}=(\texttt{1100})_2,翻转 (\texttt{0011})_2=(\texttt{3})_{16}
\hspace{23pt}\bullet\,第三个字符 (\texttt{V})_{16},跳过该字符;
\hspace{23pt}\bullet\,第四个字符 (\texttt{b})_{16}=(11)_{10}=(\texttt{1011})_2,翻转 (\texttt{1101})_2=(\texttt{D})_{16}
\hspace{23pt}\bullet\,第五个字符 (\texttt{a})_{16}=(10)_{10}=(\texttt{1010})_2,翻转 (\texttt{0101})_2=(\texttt{5})_{16}
\hspace{23pt}\bullet\,第六个字符 (\texttt{w})_{16},跳过该字符。
示例3

输入

123 15

输出

88C4A

说明

\hspace{15pt}在这个样例中,全过程描述如下:
\hspace{15pt}【合并阶段】
\hspace{23pt}\bullet\,第一步合并得到 u = \texttt{
\hspace{23pt}\bullet\,第二步排序得到 u' = \texttt{
\hspace{15pt}【调整阶段】
\hspace{23pt}\bullet\,对于第一、二个字符 (\texttt{1})_{10},其十进制数为 (1)_{10},二进制数为 (\texttt{0001})_2,翻转后得到 (\texttt{1000})_2,再转换回十六进制数为 (\texttt{8})_{16}
\hspace{23pt}\bullet\,第三个字符 (\texttt{3})_{16}=(3)_{10}=(\texttt{0011})_2,翻转 (\texttt{1100})_2=(\texttt{C})_{16}
\hspace{23pt}\bullet\,第四个字符 (\texttt{2})_{16}=(2)_{10}=(\texttt{0010})_2,翻转 (\texttt{0100})_2=(\texttt{4})_{16}
\hspace{23pt}\bullet\,第五个字符 (\texttt{5})_{16}=(5)_{10}=(\texttt{0101})_2,翻转 (\texttt{1010})_2=(\texttt{A})_{16}

备注:
本题已于下方时间节点更新,请注意题解时效性:
1. 2025-05-15 更新题面。
2. 2024-12-14 更新题面。
l = input().replace(" ","")
odds = []
evens = []
for i in range(len(l)):
    if i % 2 == 0:  # 下标1开始
        odds.append(l[i])
    else:
        evens.append(l[i])
odds_ = sorted(odds)
evens_ = sorted(evens)
u_ = ""
max_len = max(len(odds), len(evens))
for i in range(max_len):
    if i < len(odds):
        u_ += odds_[i]
    if i < len(evens):
        u_ += evens_[i]
result = []
HEX_CHAR = "0123456789abcdefABCDEF"
for ch in u_:
    if ch not in HEX_CHAR:
        result.append(ch)
    else:
        binary = ""
        binary = bin(int(ch, 16))[2:].zfill(4)
        reversed_binary = binary[::-1]
        hex_ = hex(int(reversed_binary, 2))[2:].upper()
        result.append(hex_)
print("".join(result))

发表于 2026-03-24 11:21:25 回复(0)
s,t = input().strip().split(" ")
u = list(s + t)
lu1 = []
lu2 = []
a = ""
for i,j in enumerate(u):
    if i % 2 != 0:
        lu1.append(j)
    else:
        lu2.append(j)
ls = sorted(lu1)
lt = sorted(lu2)
lb = []
if len(ls) == len(lt):
    for x in range(0,len(u)//2):
        a += lt[x] + ls[x]
if len(ls) > len(lt):
    for x in range(0,len(u)//2):
        a += lt[x] + ls[x]
    a += ls[-1]
if len(ls) < len(lt):
    for x in range(0,len(u)//2):
        a += lt[x] + ls[x]
    a += lt[-1]
for b in a:
    if 48<=ord(b)<=57&nbs***bsp;97<=ord(b)<=102&nbs***bsp;65<=ord(b)<=70:
        b = int(b,16)
        b = format(b,"04b")
        b = str(b)[::-1]
        b = hex(int(b,2))[2:].upper()
        lb.append(b)
    else:
        lb.append(b)
print("".join(map(str,lb)))

发表于 2026-03-10 17:58:16 回复(0)
累死了。
s, t = input().split(" ")
u = s + t
# print(u)

u1 = [u[_] for _ in range(1, len(u), 2)]
u2 = [u[_] for _ in range(0, len(u), 2)]
u1.sort()
u2.sort()
# print(u1)
# print(u2)

v = str()

if len(u1) < len(u2):
    for i in range(0, len(u1)):
        v += u2[i] + u1[i]
    v += u2[-1]

if len(u1) > len(u2):
    for i in range(0, len(u2)):
        v += u2[i] + u1[i]
    v += u1[-1]

if len(u1) == len(u2):
    for i in range(0, len(u2)):
        v += u2[i] + u1[i]
# print(v)

# print(ord("0")) # 48
# print(ord("9")) # 57
# print(ord("a")) # 97
# print(ord("f")) # 102
# print(ord("A")) # 65 
# print(ord("F")) # 70

A = []

for i in v:
    c1 = ord(i) >= 48 and ord(i) <= 57
    c2 = ord(i) >= 97 and ord(i) <= 102
    c3 = ord(i) >= 65 and ord(i) <= 70

    if c1&nbs***bsp;c2&nbs***bsp;c3:
        if c1:
            A.append(int(i))
        
        if c2:
            t = "1" + chr(ord(i) - 49)
            A.append(int(t))

        if c3:
            t = "1" + chr(ord(i) - 17)
            A.append(int(t))
    else:
        A.append(i)
# print(A)

B = []

def ten_to_two(n, save):
    if n == 0:
        # print(save)
        R = [0, 0, 0, 0]

        for i in save:
            R[i] = 1
        # print(R)

        s1 = str()
        # for i in range(len(R) - 1, -1, -1):
        #     s1 += str(R[i])
        for i in range(0, len(R)):
            s1 += str(R[i])
        # print(s1)

        B.append(s1)

    if n > 0:
        x = 0

        while 2 ** x <= n:
            x += 1
        
        save.append(x - 1)
        new_n = n - 2 ** (x - 1)

        ten_to_two(new_n, save)


for i in range(0, len(A)):
    if type(A[i]) == int:

        if A[i] > 0:
            ten_to_two(A[i], [])
            A[i] = B[-1]

        if A[i] == 0:
            A[i] = "0000"
# print(A)


def two_to_ten(s1):
    a = 0
    
    for i in range(0, len(s1)):
        a = a + int(s1[i]) * 2 ** (len(s1) - 1 - i)
    
    a = str(a)

    if a == "10":
        a = "A"
    if a == "11":
        a = "B"
    if a == "12":
        a = "C"
    if a == "13":
        a = "D"
    if a == "14":
        a = "E"
    if a == "15":
        a = "F"

    # print(a)
    return a


x = str()
for i in A:
    if i[0] == "0"&nbs***bsp;i[0] == "1":
        x += two_to_ten(i)
    else:
        x += i
print(x)


发表于 2026-01-16 20:32:31 回复(0)
a = input().split()
a =  list(a[0] + a[1])
a[::2] = sorted(a[::2])  
a[1::2] = sorted(a[1::2])
for i in a:
    if i.isdigit() or (i.isalpha() and i.upper()<'G'):
        print(hex(int( ''.join(reversed(bin(int(i.lower(),16) )[2:].rjust(4,"0"))) ,2))[2:].upper(),end='')
    else:
        print(i,end='')
有些细节需要注意,例如,二进制需要补0,还有转二进制的截断问题
发表于 2025-05-01 23:24:50 回复(0)
写用例的这位是不是读不懂什么叫做“仅由小写字母 a-f、大写字母 A-F、数字 0-9 构成”,读不懂就回小学重造去
发表于 2025-03-18 18:33:23 回复(0)
题目有问题,少了一个条件,测试用例中存在G-Z和g-z的字符。应该补充条件如果存在G-Z和g-z的字符,应该在u'后的处理过程中保持原样
发表于 2025-01-02 12:00:50 回复(0)
a=input().split(' ')
a=''.join(a)
l1=''
l2=''
l3=[]
l4='abcdef'
l5='ABCDEF'
for i in range(len(a)):
    if i%2==0:
        l1=l1+a[i]
    else:
        l2=l2+a[i]
l1=sorted(l1)
l2=sorted(l2)
if len(l1)==len(l2):
    for i in range(len(l1)):
        l3.append(l1[i])
        l3.append(l2[i])
elif len(l1)>len(l2):
    for i in range(len(l2)):
        l3.append(l1[i])
        l3.append(l2[i])
    for j in range(len(l2),len(l1)):
        l3.append(l1[j])
elif len(l1)<len(l2):
    for i in range(len(l1)):
        l3.append(l1[i])
        l3.append(l2[i])
    for j in range(len(l1),len(l2)):
        l3.append(l2[j])
for j in range(len(l3)):
    if l3[j] in l4:
        dou=str(bin(ord(l3[j])-87))[2:]
        dou='0b'+dou[::-1]
        dou=int(dou,2)
        l3[j]=str(dou)
    elif l3[j] in l5:
        dou=bin(ord(l3[j])-55)[2:]
        dou='0b'+dou[::-1]
        dou=int(dou,2)
        l3[j]=str(dou)
    elif l3[j].isalpha():
        l3[j]=l3[j]
    else:
        dou=bin(int(l3[j]))[2:]
        dou=dou.zfill(4)
        dou='0b'+dou[::-1]
        dou=int(dou,2)
        l3[j]=str(dou)
for i in range(len(l3)):
    if l3[i]=='10':
        l3[i]='A'
    if l3[i]=='11':
        l3[i]='B'
    if l3[i]=='12':
        l3[i]='C'
    if l3[i]=='13':
        l3[i]='D'
    if l3[i]=='14':
        l3[i]='E'
    if l3[i]=='15':
        l3[i]='F'
print(''.join(l3))

发表于 2024-09-12 01:14:20 回复(0)
感觉不像算法,而是实际碰到的需求,按照要求一步步去做就好了。有个地方要注意,题目中没有明确告诉除了a-f, A-F,之外的字母怎么处理,第一次就没有考虑到。
s = input()
s = s.replace(" ", "")


# combine and sort two string
l1 = [s[i] for i in range(len(s)) if i%2==0]
l2 = [s[i] for i in range(len(s)) if i%2==1]
l1.sort()
l2.sort()


def encrypt(c):

    # convert to binary
    c = bin(int(c, 16))[2:].rjust(4, "0")[::-1]

    # convert binary to hex
    c = hex(int(c, 2))[2:].upper()
    return c

# construct a hashmap
hmap = {str(k):encrypt(str(k)) for k in range(10)}

for i in "ABCDEFabcdef":
    hmap[i] = encrypt(i)

# convert character in string if necessary
for i in range(len(l1)):
    if l1[i] in hmap:
        l1[i] = hmap[l1[i]]
for i in range(len(l2)):
    if l2[i] in hmap:
        l2[i] = hmap[l2[i]]

res = ''
# generate result
for i in range(len(s)):
    if i%2 == 0:
        res += l1.pop(0)
    else:
        res += l2.pop(0)

print(res)


发表于 2024-06-05 14:47:44 回复(0)
a,b=input().split()
s='0123456789abcdefABCDEF'
def app():
    str1=a+b
    even = sorted(str1[::2])
    odd = sorted(str1[1::2])
    if len(even)==len(odd):
        str2=''.join(e+o for e,o in zip(even,odd))
    else:
        str2 = ''.join(e + o for e, o in zip(even, odd))+even[-1]
    lst=[i for i in str2]
    for i in range(len(lst)):
        if str2[i] in s:
            int1 = bin(int(lst[i], 16))  # 16进制转为2进制,0b开头
            int2 = int1[2:]  # 2进制表示的数字字符串
            if len(int2) < 4:
                int2 = '{:0>4}'.format(int2)
            str_bin = str(int2)[::-1]
            lst[i] = str(hex(int(str_bin,2)))[2:].upper()  # 2进制转为16进制,0x开头
        else:
            pass
    print(''.join(lst))

app()

发表于 2023-09-06 22:13:50 回复(0)
为什么测试样例里面有G这个字符啊?
为什么十六进制有G?
用例输入:Eqr v9oEb12U2ur4xu7rd931G1f50qDo
预期输出:8084842CAE9B9G7D7BUFooqqrrrvuxu
发表于 2023-08-02 23:08:14 回复(2)
s=list("".join(input().split()))
s[0::2]=sorted(s[0::2])
s[1::2]=sorted(s[1::2])
for i in s:
    try:
        i=int(i,16)
        i=bin(i)[2:].rjust(4,"0")[::-1]
        i=int(i,2)
        i=hex(i)[2:]
        if i.islower():
            i=i.upper()
        print(i,end="")
    except:
        print(i,end="")

发表于 2023-06-06 13:40:29 回复(0)
def reserve(str: str):
    return str[-1::-1]

def str2Hex2Bin2SortedHexStr(s: str):
    decimalism = int(s, 16)
    binary = bin(decimalism)[2:]
    if len(binary) < 4:
        binary = (4 - len(binary)) * "0" + binary
    binary = reserve(binary)
    hexStr = hex(int(binary, 2))[2:]
    if hexStr.isalpha():
        return hexStr.upper()
    else:
        return hexStr

def step1(str1: str, str2: str):
    return str1 + str2

def step2(mergeStr: str):
    strLength = len(mergeStr)
    evenIndexStr = []
    oddIndexStr = []
    for i in range(strLength):
        if i%2 != 0:    # odd digit index
            oddIndexStr.append(mergeStr[i])
        else:   # even digit index
            evenIndexStr.append(mergeStr[i])
    evenIndexStr = sorted(evenIndexStr)
    oddIndexStr = sorted(oddIndexStr)
    res = ""
    for i in range(len(evenIndexStr)):
        res += evenIndexStr[i]
        try:
            res += oddIndexStr[i]
        except Exception as e:
            # print(e)
            pass
    return res

def step3(sortedStr: str):
    str1 = "ABCDEF" 
    str2 = "abcdef"
    res = ""
    strList = list(sortedStr)
    for i in range(len(strList)):
        if (strList[i] in str1)&nbs***bsp;(strList[i] in str2)&nbs***bsp;(strList[i].isdigit()):
            if strList[i].isalpha():
                strList[i] = strList[i].lower()
            res += str2Hex2Bin2SortedHexStr(strList[i])
        else:
            res += strList[i]
    return res
str1, str2 = map(str, input().strip().split(" "))
print(step3(step2(step1(str1, str2))))
#冲冲冲

发表于 2023-04-26 01:23:13 回复(1)
s=input().split()
s1=s[0]+s[1]
odds=[]
odds_other=[]
#两个字符串str1和str2进行前后合并
for i in range(len(s1)):
    if i%2==0:
        odds.append(s1[i])
    else:
        odds_other.append(s1[i])
odds.sort()
odds_other.sort()
after_s1=''
#两个字符串str1和str2进行前后合并
for i in range(len(odds_other)):
    after_s1+=odds[i]+odds_other[i]
if len(odds)>len(odds_other):
    after_s1+=odds[len(odds)-1]
#两个字符串str1和str2进行前后合并
z=''
for i in after_s1:
    temp=''
    if i.isdigit():
        temp=bin(int(i))
        if len(temp[2:])<4:
            temp=(4-len(temp[2:]))*'0'+temp[2:]
    elif i.isalpha:
        if str(i.upper()) in('ABCDEF'):
            temp=bin(ord(i.upper())-55)[2:]
        else:
            z+=i
            continue
    else:
        continue  
    temp1=str(temp[::-1])
    if 'b0' in temp1:
        temp1=temp1.replace('b0','')
    if int(temp1,2)>9:
        z+=str(chr(int(temp1,2)+55)).upper()
    else:
        z+=str(hex(int(temp1,2))[2:]).upper()
print(z)
发表于 2023-01-04 18:37:05 回复(0)
进制问题,python中自带进制转换
s0, s1 = input().split()
# 转换一
s = s0 + s1
# 转换二
ji, ou = [], []
for i in range(len(s)):
    if i % 2 == 0:
        ou.append(s[i])
    else:
        ji.append(s[i])

ji.sort()
ou.sort()
tmp = 0
s = ''
while ji and ou:
    if tmp == 0:
        s += ou[0]
        ou = ou[1:]
        tmp = 1
    elif tmp == 1:
        s += ji[0]
        ji = ji[1:]
        tmp = 0
if ji: s += ji[0]
else: s += ou[0]

# 转换三
res = ''
for c in s:
    if '0' <= c <= '9'&nbs***bsp;'A' <= c <= 'F'&nbs***bsp;'a' <= c <= 'f':
        F2A = int(c, 16)
        A2B = format(F2A, '04b')
        tA2B = A2B[::-1]
        tB2A = int(tA2B, 2)
        tA2F = hex(tB2A)[2:]
        res += tA2F.upper()
    else:
        res += c

print(res)


发表于 2022-08-29 16:02:25 回复(0)
from itertools import zip_longest

def encod(char: str):
    if char.isdigit()&nbs***bsp;ord('A') <= ord(char) <= ord('F')&nbs***bsp;ord('a') <= ord(char) <= ord('f'):
        return hex(int(bin(int(char,base=16))[2:][::-1].ljust(4,'0'),base=2))[-1].upper()
    return char

def process(s1, s2):
    s = s1 + s2
    s_even = sorted(s[::2])
    s_odd  = sorted(s[1::2])

    s_new = ''.join(map(lambda x: ''.join([x[0],x[1]]),zip_longest(s_even,s_odd,fillvalue='')))
    return ''.join(map(encod,s_new))

s = input().split(' ')

print(process(s[0],s[1]))

发表于 2022-08-26 21:59:19 回复(0)
str1, str2 = map(str, input().split())
s = str1 + str2
li = list(s)
li1 = sorted(li[::2])
li2 = sorted(li[1::2])
s1 = ""
for i in range(len(li1)):
    s1 += li1[i]
    if i < len(li2):  # 第二个列表里的字符可能会少一个
        s1 += li2[i]
# print(s1)


lis = list(s1)
for j in range(len(lis)):
    if lis[j] in "0123456789ABCDEFabcdef":
        lis[j] = hex(int(bin(int(lis[j], 16))[2:].rjust(4, "0")[::-1], 2))[2:].upper()

# print(lis)      
print("".join(lis))
发表于 2022-08-24 01:01:39 回复(0)
# 初学者按照题意一步一步做的,可能没有答案写的好,请参考。
a=''.join(input().split())
l1,l2=[],[]
for i in range(0,len(a),2):
    l1.append(a[i])
l1=sorted(l1)
for i in range(1,len(a),2):
    l2.append(a[i])
l1=sorted(l1)
l2=sorted(l2)
index1,index2=0,0
s=''
for i in range(len(a)):
    if (i+2)%2==0:
        s+=l1[index1]
        index1+=1
    else:
        s+=l2[index2]
        index2+=1
m,q='',''
for one in s:
    if one.isalpha():
        if 'A'<=one<='F'or'a'<=one<='f':
            m+=hex(int(('0b'+bin(int(one,16)).replace('0b','')[::-1]),2)).replace('0x','').upper()
        else:
            m+=one
    elif one.isdigit():
        q=bin(int(one)).replace('0b','')
        q=int(((4-len(q))*'0'+q)[::-1],2)
        if q>=10:
            m+=hex(q).replace('0x','').upper()
        else:
            m+=str(q)
print(m)

'''下面是调试用的代码'''
# m='f'
# print(m,type(m))
# q=hex(int(('0b'+bin(int(m,16)).replace('0b','')[::-1]),2)).replace('0x','')
# # q=bin(int(m,16))
# print(q,type(q))

# m='5'
# q=bin(int(m)).replace('0b','')
# q=int(((4-len(q))*'0'+q)[::-1],2)
# if q>=10:
#     q=hex(q).replace('0x','').upper()
# else:
#     q=str(q)
# print(q,type(q))

发表于 2022-08-10 10:52:52 回复(0)

问题信息

难度:
57条回答 72027浏览

热门推荐

通过挑战的用户

查看代码
字符串合并处理