Topcoder竞赛题练习个人解法 about anagrams

来源

题目如下:
Problem Statement

Two words are said to be anagrams if one word can be formed by rearranging the letters of the other word. For example, “AABC” and “CABA” are anagrams.
You will be given two strings, word1 and word2, representing two words. These two strings will contain only uppercase letters (‘A’-‘Z’) and ‘.’ characters which denote missing letters. Replace the ‘.’ characters with uppercase letters such that the two words become anagrams and return the result as a vector containing exactly two elements. The first element should correspond to word1 and the second element should correspond to word2. If there are multiple possible return values, choose the one in which the first element comes first alphabetically. If ties still exist, choose the one among them in which the second element comes first alphabetically. If it is impossible to make the two words into anagrams, return an empty vector . Note that two equal words are considered anagrams.

个人解法:
单词转换为列表,标记其位置,再排个序
使两个列表的字母相等

import random
def list_sort(list,j):
    for i in range(len(list)-1):
        if list[i+1][j]<list[i][j]:
            list[i+1],list[i]=list[i],list[i+1]
    return list
def main(str1,str2):
    str1_list=[]
    for i in range(len(str1)):
        str1_list.append([i,str1[i]])
    str2_list=[]
    for i in range(len(str2)):
        str2_list.append([i,str2[i]])
    sorted_str1_list=list_sort(str1_list,1)
    sorted_str2_list=list_sort(str2_list,1)
    for i in range(len(sorted_str1_list)):
        if sorted_str2_list[i][1]!='.':
            sorted_str1_list[i][1]=sorted_str2_list[i][1]
        if sorted_str1_list[i][1]!='.':
            sorted_str2_list[i][1]=sorted_str1_list[i][1]
        if sorted_str1_list[i][1]=='.' and sorted_str2_list[i][1]=='.':
            sorted_str1_list[i][1]=sorted_str2_list[i][1]=chr(random.randint(65,89))
    new_str1_list=list_sort(sorted_str1_list,0)
    new_str2_list=list_sort(sorted_str2_list,0)
    new_str1=""
    for i in new_str1_list:
        new_str1+=i[1]
    new_str2 = ""
    for j in new_str2_list:
        new_str2 += j[1]
    return new_str1,new_str2

if __name__=="__main__":
    str1,str2=main('.','A')
    print(str1)
    print(str2)

550分的题不过如此

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值