c/c++语言开发共享C++实现LeetCode(557.翻转字符串中的单词之三)

[leetcode] 557.reverse words in a string iii 翻转字符串中的单词之三given a string, you need to reverse the orde


[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 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

参考资料:

到此这篇关于c++实现leetcode(557.翻转字符串中的单词之三)的文章就介绍到这了,更多相关c++实现翻转字符串中的单词之三内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多c/c++开发分享C++实现LeetCode(557.翻转字符串中的单词之三),都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/679653.html

(0)
上一篇 2021年8月5日
下一篇 2021年8月5日

精彩推荐