题3
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串中的空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例: “This is nowcoder”,“is This nowcoder” 返回:true “Here you are”,“Are you here” 返回:false
思路1
分别对字符串排序,然后对排序好的字符串判断是否一样,若出现不一样,返回False。
代码
class Same:
def checkSam(self
, stringA
, stringB
):
list_a
= list(stringA
)
list_b
= list(stringB
)
if list_a
==0 and list_b
== 0:
return True
list_a
.sort
()
list_b
.sort
()
list_A
= ''.join
(list_a
)
list_B
= ''.join
(list_b
)
if len(list_A
) != len(list_B
):
return False
for i
in range(len(list_A
)):
if list_A
[i
] != list_B
[i
]:
return False
return True
思路2
创建一个ASCII长度的0列表,求两个字符串的 ASCII 数值,串A +1,串B-1,最后判断列表是否全部为0.
代码
class Same:
def checkSam(self
, stringA
, stringB
):
len_a
= len(stringA
)
len_b
= len(stringB
)
if len_a
==0 and len_b
== 0:
return True
if len_a
!= len_b
:
return False
list = [0]*256
for i
in range(len_a
):
list[ord(stringA
[i
])] += 1
list[ord(stringB
[i
])] -= 1
for i
in list:
if i
!=0:
return False
return True