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