Reverse Words in a String III 翻转字符串中的单词之三
来源:互联网 发布:感恩节由来 知乎 编辑:程序博客网 时间:2024/05/18 02:54
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.
这道题让我们翻转字符串中的每个单词,感觉整体难度要比之前两道Reverse Words in a String II和Reverse Words in a String要小一些,由于题目中说明了没有多余空格,使得难度进一步的降低了。首先我们来看使用字符流处理类stringstream来做的方法,相当简单,就是按顺序读入每个单词进行翻转即可,参见代码如下:
解法一:
class Solution {public: string reverseWords(string s) { string res = "", t = ""; istringstream is(s); while (is >> t) { reverse(t.begin(), t.end()); res += t + " "; } res.pop_back(); return res; }};
下面我们来看不使用字符流处理类,也不使用STL内置的reverse函数的方法,那么就是用两个指针,分别指向每个单词的开头和结尾位置,确定了单词的首尾位置后,再用两个指针对单词进行首尾交换即可,有点像验证回文字符串的方法,参见代码如下:
解法二:
class Solution {public: string reverseWords(string s) { int start = 0, end = 0, n = s.size(); while (start < n && end < n) { while (end < n && s[end] != ' ') ++end; for (int i = start, j = end - 1; i < j; ++i, --j) { swap(s[i], s[j]); } start = ++end; } return s; }};
类似题目:
Reverse Words in a String II
Reverse Words in a String
阅读全文
0 0
- Reverse Words in a String III 翻转字符串中的单词之三
- 151. Reverse Words in a String 翻转字符串中的单词
- LeetCode刷题:Reverse Words in a String(翻转字符串中的单词)
- LeetCode 557 Reverse Words in a String III(反转字符串中的单词3)
- leetcode Reverse Words in a String III 反转字符串中的单词
- Leetcod:557.Reverse Words in a String III 反转字符串中的每个单词。
- LeetCode OJ 之 Reverse Words in a String (翻转字符串的单词)
- Reverse Words in a String 翻转字符串
- LeetCode 557. Reverse Words in a String III (字符串翻转)
- 翻转单词顺序 Reverse Words in a String
- Reverse Words in a String 翻转句子的单词
- Reverse Words in a String 翻转单词顺序
- Reverse Words in a String 翻转一个字符串里的单词顺序 @LeetCode
- leetcode151-Reverse Words in a String(翻转字符串单词的位置)
- 字符串-Reverse Words in a String(翻转字符串)
- 【LintCode】Reverse Words in a String 翻转字符串
- leetcode 151. Reverse Words in a String 字符串 翻转
- 【LintCode】Reverse Words in a String 翻转字符串
- Business Process Automation with ProcessMaker 3.1.pdf 2017 英文原版 免费下载
- ubuntu的安装nginx
- 别去霍格沃兹了!这些现实中的“魔法”比哈利波特的更酷!
- 充电8分钟狂奔1000公里的电动汽车,都哪儿去了?
- 面部识别 or 屏下指纹,谁将会是全屏时代的霸主
- Reverse Words in a String III 翻转字符串中的单词之三
- 用中文写出数字
- 多线程编程
- 背包例题【dp练习】
- 第18章,一些新功能
- 唯快不破:Linux网络编程中socket常见错误分析
- 独立显卡ubuntu+配置sublime+matlab2016
- Parsing with Perl 6 Regexes and Grammars.pdf 2017 英文原版 免费下载
- MyBatis使用