557.Reverse Words in a String III(String-Easy)
来源:互联网 发布:php干什么的 编辑:程序博客网 时间:2024/06/05 09:01
转载请注明作者和出处: http://blog.csdn.net/c406495762
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://github.com/Jack-Cherish/LeetCode
阅读全文
0 0
- 557.Reverse Words in a String III(String-Easy)
- leetcode 557. Reverse Words in a String III(easy)
- [easy]557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- shell数组和declare用法
- Git分支概念
- 分针网—每日分享:PHP接入支付宝教程
- 集合框架
- Linux网络流量实时监控ifstat iftop命令详解
- 557.Reverse Words in a String III(String-Easy)
- rabbitmq移植到arm
- 深度学习笔记——深度学习框架TensorFlow(一)
- QListWidget的插入删除方法
- 程序员经典智力面试题
- SciTe 中文设置(解决乱码,中文界面)
- java ssm使用ajax实现简单分页
- 系统调用和库函数及API的区别
- 折线分割平面