对于一个长度为 n 字符串,我们需要对它做一些变形。
首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把这个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。
比如"Hello World"变形后就变成了"wORLD hELLO"。
数据范围:
, 字符串中包括大写英文字母、小写英文字母、空格。
进阶:空间复杂度
, 时间复杂度
给定一个字符串s以及它的长度n(1 ≤ n ≤ 10^6)
请返回变形后的字符串。题目保证给定的字符串均由大小写字母和空格构成。
"This is a sample",16
"SAMPLE A IS tHIS"
"nowcoder",8
"NOWCODER"
"iOS",3
"Ios"
import sys
data = sys.stdin.readline().strip().split(",")
words = data[0].strip('"').split()
xin_words = []
for i in range(1,len(words)+1):
xin_words.append(words[-i].swapcase())
print('"'+' '.join(xin_words)+'"')
#我这样写哪里有问题,用例没有通过,请帮忙瞅瞅
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @param n int整型
# @return string字符串
#
class Solution:
def trans(self , s: str, n: int) -> str:
# write code here
# 先把空格隔开的单词存储到列表中
list_string = s.split(' ')
# 反转单子大小写并倒序输出
list_string = [word.swapcase() for word in list_string[::-1] ]
# 将反转后的列表中的单词按顺序用空格连接起来
return ' '.join(list_string)
class Solution:
def trans(self , s: str, n: int) -> str:
#边界条件考虑
if n == 0:
return s
#单词大小写变换
res = ""
for i in range(n):
#大写变小写
if s[i] <= 'Z' and s[i] >= 'A':
res += chr(ord(s[i])-(ord('A')-ord('a')))
#小写变大写
elif s[i] >= 'a' and s[i] <= 'z':
res += chr(ord(s[i])-(ord('a')-ord('A')))
#空白保留
else:
res += s[i]
#单词反序
res = list(res.split(' '))[::-1]
return ' '.join(res)
class Solution:
def trans(self , s: str, n: int) -> str:
return ' '.join([''.join([c.lower() if c.isupper() else c.upper() for c in w]) for w in s.split(' ')][::-1]) class Solution:
def trans(self , s: str, n: int) -> str:
c = 'abcdefghijklmnopqrstuvwxyz' # 小写字符集合
strlist = s.split(' ') # 根据空格分割
res = ''
for index in range(len(strlist)-1,-1,-1): # 字符串倒序处理
for i in strlist[index]:
if i in c: # 如果小写改成大写,大写改成小写
res = res + i.upper()
else:
res = res + i.lower()
res = res + ' '
res = res[:-1] # 减去最后一个空格
return res class Solution:
def trans(self, s: str, n: int) -> str:
# write code here
combine_list = []
str_ls = s.split(" ")
if len(str_ls) > 1:
for i in str_ls[::-1]:
if i.lower() == i:
combine_list.append(i.upper())
else:
fs_combine = ''
for j in i:
if j.upper() == j:
fs_combine += j.lower()
else:
fs_combine += j.upper()
combine_list.append(fs_combine)
return ' '.join(combine_list)
else:
combine = ""
for i in s:
if i == i.upper():
combine += i.lower()
else:
combine += i.upper()
return combine class Solution:
def trans(self , s: str, n: int) -> str:
# write code here
def do(s):
res=''
for i in s:
tmp=i
if ord('a')<=ord(tmp)<=ord('z'):
tmp=chr(ord(tmp)-32)
elif ord('A')<=ord(tmp)<=ord('Z'):
tmp=chr(ord(tmp)+32)
res+=tmp
return res
ss=s.split(' ')
res=[]
for s in ss:
res.append(do(s))
return ' '.join(res[::-1])