文章目录
字符串基本操作
字符编码
1781 · 反转ASCII编码字符串
描述
给定一个由ascii编码的字符串(例如,“ABC”可以编码为“656667”),您需要编写一个将编码字符串作为输入并返回反转的解码字符串的函数。
def reverseAsciiEncodedString(self, encodeString):
# Write your code here
i = 0
ss = ""
while i + 2 <= len(encodeString):
ss += chr(int(encodeString[i:i+2]))
i += 2
return ss[::-1]
老师的代码:
时间复杂度
回文串
1784 · 减小为回文
给定一个由 a-z 组成的字符串 s. 欲通过以下操作把 s 变成回文串:
我没理解他abc,变成abb之后,他怎么只改变了最后的b,不是应该都改吗?如果你只改了最后的b。那么样例2,abcd-abcc-abcb-abca。也不对啊。
class Solution:
"""
@param s: the string s
@return: the number of operations at least
"""
def numberOfOperations(self, s):
# Write your code here
count = 0
cur_max = max(s)
cur_min = min(s)
while cur_max != cur_min:
s = s.replace(cur_max, chr(ord(max(s))-1))
if not self.identify_palindrome(s):
count += 1
cur_max = max(s)
else:
return count
return -1
def identify_palindrome(self, ss):
l, r = 0, len(ss) - 1
while l <= r:
if ss[l] != ss[r]: return False
return True
看了老师的思路,改的代码:
def numberOfOperations(self, s):
# Write your code here
l, r = 0, len(s) - 1
count = 0
while l <= r:
count += abs(ord(s[r]) - ord(s[l]))
l += 1
r -= 1
return count
下面是老师的代码:
958 · 回文数据流
一个数据流进来,每次一个小写字母,当前数据流的排列是否能组成回文串。
我写的代码,在pycharm可以跑,到了平台就跑不了,不知道为什么。听了老师讲的,题目问的是能否组成回文串,也就是说不用必须按照现在的顺序。
class Solution:
"""
@param s: The data stream
@return: Return the judgement stream
"""
def getStream(self, s):
# Write your code here
res = []
ss = ""
for i in s:
ss += i
if self.identify_palindrome(ss): res.append(1)
else: res.append(0)
return res
def identify_palindrome(self, ss):
l, r = 0, len(ss) - 1
while l <= r:
if ss[l] != ss[r]: return False
l += 1
r -= 1
return True
看了老师讲的视频,改的代码:
def getStream(self, s):
# Write your code here
if not s or len(s) == 0: return []
res = [0 for _ in range(len(s))]
letters = [0 for _ in range(26)]
odd_count = 0
for i, cha in enumerate(s):
letters[ord(cha) - ord('a')] += 1
if letters[ord(cha) - ord('a')] % 2 == 1:
odd_count += 1
else:
odd_count -= 1
res[i] = 0 if odd_count > 1 else 1
return res
1819 · 最长双交替子串
给定一个长度为NN且只包含a和b的字符串SS。你需要找出最长的子串长度,使得其中不包含三个连续的字母。即,找出不包含aaa或bbb的最长子串长度。注意SS是其本身的子串。
def longestSemiAlternatingSubstring(self, s):
# write your code here
if not s or len(s) == 0: return 0
l, r = 0, 1
count, res = 2, -1
if s[l] == s[r]: temp = 2
else: temp = 1
while r < len(s) - 1:
while temp != 3 and r < len(s) - 1:
if s[r] == s[r + 1]:
temp += 1
count += 1
r += 1
else:
temp = 1
count += 1
r += 1
if temp == 3:
count -= 1
l = r - 1
temp -= 1
res = max(res, count)
count = 2
return res
我发现当我的思路是连贯的时候,还好。但是如果出现了bug,我的脑子容易跟不上节奏,而且感觉无法想的更深入,也不知道怎么修改bug。真是让人心碎。
注意⚠️:老师说,刷题一定要按照类型刷,不要东一道,西一道。另外,画图!!!非常重要!!!画图!画图!画图!