文章目录
936 · 首字母大写
输入一个英文句子,将每个单词的第一个字母改成大写字母
def capitalizesFirst(self, s):
# Write your code here
if not s: return ""
ss = ""
ss += s[0].upper()
cur = 1
while cur < len(s):
if s[cur - 1] == " " and s[cur]:
ss += s[cur].upper()
else:
ss += s[cur]
cur += 1
return ss
一开始想用list,但是发现
看到的一些好的答案:
def capitalizesFirst(self, s):
string = ""
for i, char in enumerate(s):
if char.isalpha():
if i == 0 or s[i-1] == ' ':
char = char.upper()
string += char
return string
isalpha这个方法用的好。
def capitalizesFirst(self, s):
# Write your code here
array = s.split(" ")
ans = " "
return ans.join(string.capitalize() for string in array)
这个方法可以成功的原因是他用了split(" “),而不是split(”")。这样的话就可以保证中间有很多空格也考虑在内。
def capitalizesFirst(self, s):
# Write your code here
return s.title()
491 · 回文数
判断一个正整数是不是回文数。
回文数的定义是,将这个数反转之后,得到的数仍然是同一个数。
方法一:
def isPalindrome(self, num):
# write your code here
if num <= 0: return False
s = str(num)
left, right = 0, len(s) - 1
while left <= right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
方法二:
def isPalindrome(self, num):
# write your code here
if num < 0: return False
s = str(num)
mid = len(s) // 2
return s[:mid] == s[-1:mid:-1] if len(s) & 1 == 1 else s[:mid] == s[-1:mid-1:-1]
133 · 最长单词
给一个词典,找出其中所有最长的单词。
挑战:
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
def longestWords(self, dictionary):
# write your code here
max_len = len(dictionary[0])
res = [dictionary[0]]
for i in dictionary[1:]:
if len(i) > max_len:
max_len = len(i)
res = [i]
elif len(i) == max_len:
res.append(i)
return res
切片的复杂度是O(k)
列表操作,一些常见的复杂度:
看到一个好的答案,其实这个答案是用了2次循环的,因为filter第二个参数是一个可循环的变量。它循环执行了匿名函数。
def longestWords(self, dictionary):
# write your code here
max_len = max([len(i) for i in dictionary])
return list(filter(lambda x:len(x)>=max_len,dictionary))
自己写了一遍那:
def longestWords(self, dictionary):
# write your code here
max_len = max([len(i) for i in dictionary])
return list(filter(lambda x: len(x) == max_len, dictionary))
422 · 最后一个单词的长度
给定一个字符串, 包含大小写字母、空格 ’ ',请返回其最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
def lengthOfLastWord(self, s):
# write your code here
if not s: return 0
li = s.split()
if li[-1]:
return len(li[-1])
else:
return 0
not False 是True,但是not ‘ ’,结果是False,因为空字符串不等于False。‘ ’也是有字符。
353 · 最大字母
给定字符串S,找到最大的字母字符,其大写和小写字母均出现在S中,则返回此字母的大写,若不存在则返回"NO"。
python for-else 和 while-else 这两个else的执行都是for和while循环正常运行完,如果中间有break,则else的内容不会被执行。
def largestLetter(self, s):
# write your code here
low, up = [], []
for i in s:
if 'A' <= i <= 'Z':
up.append(i)
elif 'a' <= i <= 'z':
low.append(i)
if up and low:
return max(up)
else:
return 'NO'
想了半天,都没想到很好的方法。现在也代码也不追求把return什么写到一行了,那样代码可读性可能会降低。别秀。
看完答案发现自己理解错题了,麻烦请你把题目理解了,再做题好吗???
def largestLetter(self, s):
# write your code here
existing = set(s)
for i in range(25, -1, -1):
if chr(ord('A') + i) in existing and chr(ord('a') + i) in existing:
return chr(ord('A') + i)
else:
return 'NO'
8 · 旋转字符串
给定一个字符串str和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。对于不同的语言,str将以不用的形式给出,例如对于字符串 “abc” ,将以下面的形式给出。
Python:str = [‘a’, ‘b’, ‘c’]
写了一个切片,但是无论怎么返回都不行,可能是在原地反转出了问题。
def rotateString(self, str: List[str], offset: int):
# write your code here
offset_r = offset % len(str)
str = List[str[-offset_r:] + str[:-offset_r]]
return str
看了官方答案改了下:
def rotateString(self, str: List[str], offset: int):
# write your code here
if not str: return ""
offset_r = offset % len(str)
temp = (str + str)[len(str) - offset_r : 2 * len(str) - offset_r]
for i in range(len(temp)):
str[i] = temp[i]
答案真的很巧妙。学习了。