242. 有效的字母异位词(Easy)
方法一:排序
class Solution(object):
def isAnagram(self, s, t):
return sorted(s) == sorted(t)
方法二:哈希表
统计 s 和 t 中每一个字符出现的次数
class Solution(object):
def isAnagram(self, s, t):
return collections.Counter(s) == collections.Counter(t)
class Solution(object):
def longestPalindrome(self, s):
letter_num = collections.Counter(s)
flag = 0
res = 0
for value in letter_num.values():
if value%2:
flag = 1
res += value-1
else:
res += value
return res + flag
class Solution(object):
def isIsomorphic(self, s, t):
relation = {}
for i in range(len(s)):
if s[i] in relation:
if relation[s[i]] != t[i]:
return False
else:
if t[i] in relation.values():
return False
relation[s[i]] = t[i]
return True
中心拓展
如果回文字符串的长度为偶数,就从中间两个字符逐渐向外走,逐一匹配。
如果回文字符串的长度为奇数,就从中间一个字符逐渐向外走,逐一匹配。
class Solution(object):
res = 0
def countSubstrings(self, s):
n = len(s)
def maxlen(left, right):
while 0 <= left <= right < n and s[left] == s[right]:
left -= 1
right += 1
self.res += 1
return right-left-1
for i in range(n):
maxlen(i, i)
maxlen(i, i+1)
return self.res
时间复杂度:O(n
2
)
空间复杂度:O(1)
方法一:反转数字后半部分
class Solution(object):
def isPalindrome(self, x):
if x < 0 or (x%10 ==0 and x != 0):
return False
right = 0
while x > right:
right = right * 10 + x%10
x = x//10
return right == x or x == right//10
"""
:type x: int
:rtype: bool
"""
时间复杂度:O(log n)
空间复杂度:O(1)
方法二:将数字转换为字符串,并检查字符串是否为回文。
class Solution(object):
def isPalindrome(self, x):
return str(x) == str(x)[::-1]
将字符串 s 按照 0 和 1 的连续段分组,存在数组中,例如 s = 00111011,可以得到这样的 {2,3,1,2}。数组中两个相邻的数一定代表的是两种不同的字符。假设数组中两个相邻的数字为 u 或者 v,它们能组成的满足条件的子串数目为 min{u,v}。将相邻的数对较小值相加即可得到答案。
可以不用数组,我们只需要知道当前连续的数字出现的次数和上次连续数字出现的次数,取最小值即可。
class Solution(object):
def countBinarySubstrings(self, s):
pre,cur = 0, 1
res = 0
for i in range(1, len(s)):
if s[i] == s[i-1]:
cur += 1
else:
res += min(pre, cur)
pre = cur
cur = 1
return res + min(pre, cur)
796. 旋转字符串(Easy)
方法一:穷举,将字符串一次移位,看是否和目标字符串相等
class Solution(object):
def rotateString(self, A, B):
if len(A) != len(B):
return False
if not A:
return True
n = len(A)
for i in range(n):
newA = A[i:] + A[:i]
if newA == B:
return True
return False
方法二:
判断 B 是否为 A + A 的子串
class Solution(object):
def rotateString(self, A, B):
return len(A) == len(B) and B in A + A
文章来源互联网,如有侵权,请联系管理员删除。邮箱:417803890@qq.com / QQ:417803890
Python Free
邮箱:417803890@qq.com
QQ:417803890
皖ICP备19001818号-4
© 2019 copyright www.pythonf.cn - All rights reserved
微信扫一扫关注公众号:
Python Free