557.Reverse Words in a String III(String-Easy)
发布日期:2021-06-30 11:46:55
浏览次数:2
分类:技术文章
本文共 1603 字,大约阅读时间需要 5 分钟。
转载请注明作者和出处:
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
题目:反转字符串。给定一个字符串,保留字符串中空格和每个单词的顺序,反转每个单词。
思路:以空格为标志,对每个小结的单词进行操作
Language : cpp
class Solution {public: string reverseWords(string s) { int front = 0; //记录空格后第一个字符的位置 int str_length = s.length(); //字符串长度 for(int i = 0; i <= str_length; i++) { if(i == s.length() || s[i] == ' ') { //找到空格反转,没有空格整个字符串反转 reverse(&s[front], &s[i]); front = i + 1; } } return s; }};
Language : python
第一种最笨的方法:先使用split以空格为标志分开字符串,然后对每个字符串进行反转操作,再将字符串进行拼接。
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ result = '' input_str = s.split(' ') for each in input_str: result = result + each[::-1] + ' ' return result[:-1]
第二种方法,对于第一种方法进行了改进,使用join进行拼接。
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ' '.join(x[::-1] for x in s.split())
第三种方法,不实用迭代方法,加快运行速度。首先反转每个单词的顺序,然后反转整个字符串:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ' '.join(s.split()[::-1])[::-1]
我的LeetCode代码获取:
转载地址:https://jackcui.blog.csdn.net/article/details/73457057 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年05月01日 01时59分16秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
mysql5.7使用GTID特性搭建主从复制
2019-04-30
hive 数据倾斜问题汇总
2019-04-30
和面试官谈一谈高并发场景下锁的使用技巧
2019-04-30
六、DDE服务器函数
2019-04-30
八、国际化函数
2019-04-30
九、库管理函数
2019-04-30
十、数值计算函数
2019-04-30
十一、打印和打印机设置函数
2019-04-30
十二、注册表操作函数
2019-04-30
C++的除法需要留意的几点情况
2019-04-30
C++打印三角形、四边形
2019-04-30
C++程序的基本组成简介
2019-04-30
JavaScript变量及访问方式介绍
2019-04-30
centos7 hbase1.4.13+hadoop2.7.1+单机环境搭建
2019-04-30
十四、系统与环境函数
2019-04-30
十五、定时函数
2019-04-30
十三、字符串操作函数
2019-04-30
十八、垃圾收集函数
2019-04-30
十七、类定义查找函数
2019-04-30
十六、窗口操作函数
2019-04-30