• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现LeetCode(557.翻转字符串中的单词之三)

c++ 搞代码 4年前 (2022-01-06) 18次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C++实现LeetCode(557.翻转字符串中的单词之三),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[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 j=end - 1; j; ++i, --j) swap(s[i], s[j]); } start=++end; return s; };

类似题目:

Reverse Words in a String II

Reverse Words in a String

参考资料:

https:来源gao@!dai!ma.com搞$$代^@码!网//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.翻转字符串中的单词之三)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(557.翻转字符串中的单词之三)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址