首页 > 试题广场 >

字符串变形

[编程题]字符串变形
  • 热度指数:176225 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
对于一个长度为 n 字符串,我们需要对它做一些变形。

首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把这个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。

比如"Hello World"变形后就变成了"wORLD hELLO"。

数据范围: , 字符串中包括大写英文字母、小写英文字母、空格。
进阶:空间复杂度 , 时间复杂度

输入描述:
给定一个字符串s以及它的长度n(1 ≤ n ≤ 10^6)


输出描述:
请返回变形后的字符串。题目保证给定的字符串均由大小写字母和空格构成。
示例1

输入

"This is a sample",16

输出

"SAMPLE A IS tHIS"
示例2

输入

"nowcoder",8

输出

"NOWCODER"
示例3

输入

"iOS",3

输出

"Ios"
一行代码:
    def trans(self , s: str, n: int) -> str:
        return ' '.join(''.join([c.lower() if c.isupper() else c.upper() for c in s]).split(' ')[::-1])


发表于 2025-07-06 15:22:59 回复(0)
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)+'"')
#我这样写哪里有问题,用例没有通过,请帮忙瞅瞅

发表于 2025-03-07 15:09:20 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @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)


发表于 2025-01-05 21:55:37 回复(1)
k:str="" while True:
    x=input("请输入一个任意字符串:")
    y=int(input("它的长度是(空格也算):")) if y == len(x):
        z = x.swapcase().split()[::-1] for i in z:
            k=k+i+" "  print(k) break  else: print("抱歉,你输入的字符串长度不匹配,请重新输入!") continue 
发表于 2024-09-16 12:26:19 回复(0)
class Solution:
    def trans(self , s: str, n: int) -> str:
        s = s[::-1]
        # 全部反转
        s = s.swapcase()
        # 大小写互换
        ls = list(s)
        result = []
        flag = 0
        # flag用来标记空格,判断是直接加入还是反转再加入
        j = 0
        # 记录切片的起点
        for i in range(n):
            if ls[i] != ' ':
                flag = 1
                # flag为1说明此处不是一个空格
                if i == n-1:
                    result.append(''.join(reversed(s[j:])))
                # 在遍历结束时如果没有遇到空格,就把剩下的一个单词反转加入列表
            elif ls[i] == ' ' and flag == 0:
                # flag为0且遍历到一个空格,说明是连续空格,直接将空格加入列表即可
                result.append(ls[i])
                j = i + 1
                # 切片以下一个字符为起点
            elif ls[i] == ' ' and flag == 1:
                # flag为1且遍历到一个空格,说明一个单词已经遍历结束,将该单词反转加入列表
                result.append(''.join(reversed(s[j:i])))
                result.append(' ')
                j = i + 1
                # 切片以下一个字符为起点
                flag = 0
                # flag设置为0,说明刚刚有一个单词加入列表
        return ''.join(result)
发表于 2024-07-30 18:42:13 回复(2)
class Solution:
    def trans(self , s: str, n: int) -> str:
        splited_list=s.split(" ")
        splited_list.reverse()
        return  " ".join(splited_list).swapcase()

发表于 2024-05-01 11:25:57 回复(0)
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)
                

编辑于 2024-04-11 15:48:47 回复(0)
简单的:
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        s=s.swapcase()
        out=s.split(' ')
        return ' '.join(out[::-1])

复杂的:
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        t=''
        #大小写互换
        for i in s:
            if i.islower():
                t+=i.upper()
            elif i.isupper():
                t+=i.lower()
            else:t+=i
        li=t.split(' ')
        #各单词顺序颠倒
        l=0
        r=len(li)-1
        while l<r:
            li[l],li[r]=li[r],li[l]
            l+=1
            r-=1
        return ' '.join(li)

编辑于 2024-04-09 15:20:33 回复(0)
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        return ' '.join(reversed(s.swapcase().split(' ')))

发表于 2023-10-08 21:48:08 回复(1)
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        return " ".join(s.split(" ")[::-1]).swapcase()
发表于 2023-09-26 06:41:41 回复(0)
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])

发表于 2023-09-06 23:03:10 回复(0)
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        sTemp = s.split(' ')
        left = 0
        right = len(sTemp)-1
        while left < right:
            sTemp[left],sTemp[right] = sTemp[right], sTemp[left]
            left += 1
            right -= 1
        print(sTemp)
        str2 = ''
        for str1 in sTemp:
            strTemp = ''
            for i in str1:
                if i.isupper():
                    strTemp += i.lower()
                else:
                    strTemp += i.upper()
            str2 +=  strTemp
            str2 += ' '
        print(str2)
        return str2[:-1]
       
发表于 2023-08-16 17:36:02 回复(0)
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

发表于 2023-04-19 17:56:10 回复(0)
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        if n==0:
            return s
        s=list(s)
        #先对字符串进行大小写颠倒操作
        for i in range(n):
            if s[i].isupper():
                s[i]=s[i].lower()
            elif s[i].islower():
                s[i]=s[i].upper()
        s="".join(s) #形成新串
        #对新串进行位置颠倒操作
        slist=s.split(' ')
        st=[]
        for i in slist[::-1]:
            st.append(i)
        res=" ".join(st)
        return res
发表于 2023-02-24 19:31:43 回复(0)
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


发表于 2022-10-07 10:33:47 回复(0)
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])

发表于 2022-02-24 19:58:17 回复(0)
class Solution:
    def trans(self , s: str, n: int) -> str:
        # write code here
        s0=[]
        for i in s:
            if i!=' ':
                if i.islower():
                    s0.append(i.upper())
                else:
                    s0.append(i.lower())
            else:
                s0.append(' ')
        s0=''.join(s0).split(' ')
        return ' '.join(s0[::-1])

发表于 2022-01-05 10:12:59 回复(1)

问题信息

难度:
19条回答 22829浏览

热门推荐

通过挑战的用户

查看代码
字符串变形