经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++实现LeetCode(557.翻转字符串中的单词之三)
来源:jb51  时间:2021/8/4 17:55:40  对本文有异议

[LeetCode] 557.Reverse Words in a String III 翻转字符串中的单词之三

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 IIReverse Words in a String要小一些,由于题目中说明了没有多余空格,使得难度进一步的降低了。首先我们来看使用字符流处理类stringstream来做的方法,相当简单,就是按顺序读入每个单词进行翻转即可,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. string reverseWords(string s) {
  4. string res = "", t = "";
  5. istringstream is(s);
  6. while (is >> t) {
  7. reverse(t.begin(), t.end());
  8. res += t + " ";
  9. }
  10. res.pop_back();
  11. return res;
  12. }
  13. };

下面我们来看不使用字符流处理类,也不使用STL内置的reverse函数的方法,那么就是用两个指针,分别指向每个单词的开头和结尾位置,确定了单词的首尾位置后,再用两个指针对单词进行首尾交换即可,有点像验证回文字符串的方法,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. string reverseWords(string s) {
  4. int start = 0, end = 0, n = s.size();
  5. while (start < n && end < n) {
  6. while (end < n && s[end] != ' ') ++end;
  7. for (int i = start, j = end - 1; i < j; ++i, --j) {
  8. swap(s[i], s[j]);
  9. }
  10. start = ++end;
  11. }
  12. return s;
  13. }
  14. };

类似题目:

Reverse Words in a String II

Reverse Words in a String

参考资料:

https://discuss.leetcode.com/topic/85773/nothing-fancy-straight-java-stringbuilder

https://discuss.leetcode.com/topic/85797/java-two-methods-3-line-using-built-in-and-char-array

到此这篇关于C++实现LeetCode(557.翻转字符串中的单词之三)的文章就介绍到这了,更多相关C++实现翻转字符串中的单词之三内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号