Leetcode:反转字符串中的单词III

题目描述

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

思路分析:

方法一:
先将单词依空格分块,分别用[::-1]反向输出后再用join()依空格拼接。

代码1

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        news = s.split()   #将s中字符串以‘ ’为界进行分割,变成['Let's', 'take ', 'LeetCode', 'contest']
        lis = []   #lis为新列表
        for word in news:  #word在news列表中
            lis.append(word[::-1])  #将news的每个单词反转
        return ' '.join(lis)  #join是将lis里的字符串通过‘ ’连接
        

方法二:

  1. 对整个字符串做两次翻转实现反转字符串
  2. 第一次整体反转, 整个字符串逆序.(s[::-1])
  3. 第二次单词次序反转, 对反转字符串分割为单词列表(s[::-1].split()), 对单词次序反转(s[::-1].split()[::-1]).

代码2:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join(s[::-1].split()[::-1])

因为这里用到了python的split()函数,所以补充一下该函数的用法。

一、函数说明

1、split()函数
语法:str.split(str=“”,num=string.count(str))[n]
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表

参数说明:

str:表示为分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等,但是不能为空(“”)。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]:表示选取第n个分片

注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略

二、分离字符串例子

string =Nice.to.see.you

1.以‘.’为分隔符

print(string.split(‘.’))

[‘Nice’, ‘to’, ‘see’, ‘you’]

2.分割两次

print(string.split(‘.’,2))

[‘Nice’, ‘to’, ‘see.you’]

3.分割两次,并取序列为1的项

print(string.split(‘.’,2)[1])

to

4.分割两次,并把分割后的三个部分保存到三个文件

u1, u2, u3 =string.split(‘.’,2)

print(u1)—— Nice

print(u2)—— to

print(u3) ——see.you

### C语言实现LeetCode 151题(反转字符串中的单词) 对于给定的任务,在C语言中解决该问题的一种方法是通过手动处理字符串并利用辅助函数来完成特定操作。下面展示了一种可能的解决方案,其中包含了如何定义必要的功能以及它们是如何协同工作的解释。 #### 完整代码示例 ```c #include <stdio.h> #include <string.h> void trim(char *str) { char *end; while (isspace((unsigned char)*str)) str++; end = str + strlen(str) - 1; while(end > str && isspace((unsigned char)*end)) end--; *(end+1) = '\0'; } void reverseString(char* start, char* end){ while(start<end){ char temp=*start; *start++=*end; *end--=temp; } } char* reverseWords(char* s) { int length=strlen(s); if(length==0)return ""; // Trim leading and trailing spaces trim(s); char *result=(char*)malloc(strlen(s)+2); // Extra space for potential extra space at the end and null terminator result[0]='\0'; char word[50]; // Assuming no single word will exceed this limit int index=0; for(int i=0;i<=length;i++){ if(i==length || s[i]==' '){ if(index>0){ reverseString(word,word+index-1); strcat(result,word); if(i!=length)strcat(result," "); memset(word,'\0',sizeof(word)); index=0; } }else{ word[index++]=s[i]; } } return result; } ``` 此程序首先移除了输入字符串两端多余的空白字符[^1]。接着遍历整个字符串,每当遇到空格或到达字符串结尾时,就调用`reverseString()`函数翻转当前收集到的一个完整的词,并将其追加到最终的结果串后面。为了防止最后多出不必要的空格,在每次添加新词之前会检查当前位置是否为原字符串的实际末端位置[^2]。 注意这里假设单个词语长度不会超过预设的最大值(这里是49),如果存在更长的情况,则需要调整数组大小或者采用动态分配的方式存储临时变量`word`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值