首页 > 试题广场 >

字符串合并处理

[编程题]字符串合并处理
  • 热度指数:215050 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}定义“调整”操作为,对于一个十进制数字,将其转换为二进制数,翻转,再转换为十六进制数(大写)。例如,(\texttt{4})_{10} 对应的二进制数为 (\texttt{100})_2 ,翻转后得到 (\texttt{001})_2 ,再转换为十六进制数为 (\texttt{1})_{16}

\hspace{15pt}对于给定的仅由小写字母 \texttt{a-f} 、大写字母 \texttt{A-F} 、数字 \texttt{0-9} 构成的字符串 st ,请按照以下步骤进行处理:
\hspace{23pt}\bullet\,第一步,将 st 合并,形成一个新字符串 u
\hspace{23pt}\bullet\,第二步,将 u 中奇数位字符从小到大进行排序,随后将偶数位字符也从小到大进行排序,得到 u'
\hspace{23pt}\bullet\,第三步,对 u' 中的字符依次转换为十进制数,随后执行“调整”操作。
\hspace{15pt}输出最终的字符串。

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


输出描述:
\hspace{15pt}在一行上输出一个字符串,代表最终的字符串。
示例1

输入

dec fab

输出

5D37BF

说明

\hspace{15pt}在这个样例中,第一步合并后得到 u = \texttt{ ;第二步,排序得到 u' = \texttt{ ;随后,按位转换为十进制数,并执行“调整”操作:
\hspace{23pt}\bullet\,对于第一个字符 (\texttt{ ,其十进制数为 (10)_{10} ,二进制数为 (\texttt{1010})_2 ,翻转后得到 (\texttt{0101})_2 ,再转换回十六进制数为 (\texttt{5})_{16}
\hspace{23pt}\bullet\,对于第二个字符 (\texttt{ ,翻转后得到 (\texttt{1101})_2=(\texttt{D})_{16}
\hspace{23pt}\bullet\,对于第三个字符 (\texttt{ ,翻转后得到 (\texttt{0011})_2=(\texttt{3})_{16}
\hspace{23pt}\bullet\,对于第四个字符 (\texttt{ ,翻转后得到 (\texttt{0111})_2=(\texttt{7})_{16}
\hspace{23pt}\bullet\,对于第五个字符 (\texttt{ ,翻转后得到 (\texttt{1011})_2=(\texttt{B})_{16}
\hspace{23pt}\bullet\,对于第六个字符 (\texttt{ ,翻转后得到 (\texttt{1111})_2=(\texttt{F})_{16}
示例2

输入

ab CD

输出

3B5D

说明

\hspace{15pt}在这个样例中,第一步合并后得到 u = \texttt{ ;第二步,排序得到 u' = \texttt{ 。需要特别注意的是,这里的排序是按照 \sf{Ascii} 码表的顺序进行排序的。
示例3

输入

123 15

输出

88C4A
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)