python_lintcode_702Concatenated String with Uncommon Characters of Two Strings

本文介绍一种算法,该算法接收两个字符串作为输入,去除第一个字符串中的第二个字符串的重复字符,并将第二个字符串中未出现在第一个字符串中的字符追加到第一个字符串的剩余部分之后。通过两种方法实现这一目标:直接遍历比较法和使用计数器记录每个字符出现次数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

702Concatenated String with Uncommon Characters of Two Strings

题目

http://www.lintcode.com/zh-cn/problem/concatenated-string-with-uncommon-characters-of-two-strings/#

Two strings are given and you have to modify 1st string such that all the common characters of the 2nd strings have to be removed and the uncommon characters of the 2nd string have to be concatenated with uncommon characters of the 1st string.

样例
Given s1 = aacdb, s2 = gafd
return cbgf

Given s1 = abcs, s2 = cxzca;
return bsxz

思路

  • 题目要求:找到两个字符串之间不重复的字符,其中注意:返回的结果必须按着在字符串本身的顺序,并且若某个字符不是两字符串的重复字符,在字符串1有多次出现,都需要表示出来多个相同字符,而不是一个
你的输入
"aaabcs"
"cxzc"
你的输出
"aaabsxz"
  • 第一种思路是直接遍历两个字符串,找到互相的不重复字符
  • 第二种思路:本题要求就是找到不同的各个字母,字母一共有26个,则分别为字符串1和字符串2设置26个计数器,初始化为0,对字符串进行计数,然后分别判断字符串在对方的计数器中是否为0,如果是0,则代表这是不重复的字符。

代码

class Solution:
    """
    @param: : the 1st string
    @param: : the 2nd string
    @return: uncommon characters of given strings
    """

    def concatenetedString(self, s1, s2):
        # write your code here
        if s1 is None:return s2
        if s2 is None:return s1
        result=''
        for i in s1:
            if i in s2:
                continue
            result+=i
        for j in s2:
            if j in s1:
                continue
            result +=j
        return result
class Solution:
    """
    @param: : the 1st string
    @param: : the 2nd string
    @return: uncommon characters of given strings
    """

    def concatenetedString(self, s1, s2):
        # write your code here
        if s1==None:return s2
        if s2==None:return s1
        #定义两个列表。存放26个字母
        zimu1 = [0]*26
        zimu2 =[0]*26

        for i in s1:
            #oed()返回ascii码
            post=ord(i)-ord('a')
            zimu1[post]+=1
        for j in s2:
            post=ord(j)-ord('a')
            zimu2[post]+=1
        result=''
        for  i in s1:
            post=ord(i)-ord('a')
            if zimu2[post]==0:
                result+=i
        for  i in s2:
            post=ord(i)-ord('a')
            if zimu1[post]==0:
                result+=i
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值