描述:
字符串置换
原题地址:http://www.lintcode.com/zh-cn/problem/string-permutation/#
给定两个字符串,请设计一个方法来判定其中一个字符串是否为另一个字符串的置换。
置换的意思是,通过改变顺序可以使得两个字符串相等。
样例:
"abc" 为 "cba" 的置换。
"abcs" 为 "csba" 的置换。
"aabc" 不是 "abcc" 的置换。
思路:
刚开始以为的倒置是字符串倒置即'abcd'与'dcba',写完代码测试后一看错了并非如此,而是要A,B两个字符串的字母个数完全相同。
参考:http://www.imooc.com/wenda/detail/315319
代码:
class Solution:
"""
@param: A: a string
@param: B: a string
@return: a boolean
"""
def Permutation(self, A, B):
# write your code here
# 关键是统计字母的个数并进行判断
import string
B = list(B)
A = list(A)
# 判断两个字符串中的字母个数是否相等,如果不相等直接返回False
if len(A) != len(B):
return False
lt = string.ascii_lowercase
LT = string.ascii_uppercase
A_result = []
B_result = []
for value in lt:
A_result.append(A.count(value))
B_result.append(B.count(value))
for value in LT:
A_result.append(A.count(value))
B_result.append(B.count(value))
if B_result == A_result:
return True
else:
return False
修改
def Permutation(self, A, B):
from collections import Counter
counter_a = Counter(A)
counter_b = Counter(B)
if counter_a == counter_b:
return True
else:
return False
学习:
import string
string.assic_lowercase # 所有的小写字母
string.assic_uppercase # 所有的大写字母
# 因为字符串不能像列表一样进行修改,所以有时根据字符串创建列表非常有用
B = list(B)
# 列表方法
B = []
B.append('str') # 在列表末尾追加新的对象
# !!append()方法不是简单的返回一个修改过的列表,而是直接修改原来的列表
# 不能使用B[1] = 'str' # 会引发IndexError: list assignment index out of range
count()方法:用来统计某个元素在列表中出现的个数
B_result.append(B.count(value)) # 统计每一个字母的个数并存入数组B_result
网友评论