博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Words in a String II
阅读量:6270 次
发布时间:2019-06-22

本文共 1485 字,大约阅读时间需要 4 分钟。

Problem Description:

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,

Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Since this problem has guaranteed that the string does not contain all the leading and trailing spaces and all words are separated by a single space, it will be much easier to be solved in space. The idea is to reverse the whole string first. Then we visit the string from left to right, each time we meet a space, we reverse the immediate word before it.

The code is as follows.

1 class Solution { 2 public: 3     void reverseWords(string &s) { 4         reverse(s.begin(), s.end()); 5         s += ' '; 6         int i = 0, j = 0, n = s.length(); 7         while (i < n && j < n) { 8             while (j < n && s[j] != ' ') j++; 9             if (j < n) {10                 reverseBetween(s, i, j - 1);11                 i = j + 1;12                 j = i;13             }14         }15         s.resize(n - 1);16     }17 private:18     void reverseBetween(string &s, int i, int j) {19         while (i < j)20             swap(s[i++], s[j--]);21     }22 };

Note that we append a space to the reversed string to facilitate the detection of the last word.

转载于:https://www.cnblogs.com/jcliBlogger/p/4600353.html

你可能感兴趣的文章
Vue实例初始化的选项配置对象详解
查看>>
PLM产品技术的发展趋势 来源:e-works 作者:清软英泰 党伟升 罗先海 耿坤瑛
查看>>
vue part3.3 小案例ajax (axios) 及页面异步显示
查看>>
软件测试(二)之 Failure, Error & Fault
查看>>
浅谈MVC3自定义分页
查看>>
.net中ashx文件有什么用?功能有那些,一般用在什么情况下?
查看>>
select、poll、epoll之间的区别总结[整理]【转】
查看>>
CSS基础知识(上)
查看>>
PHP中常见的面试题2(附答案)
查看>>
26.Azure备份服务器(下)
查看>>
mybatis学习
查看>>
LCD的接口类型详解
查看>>
C#中使用RabbitMQ收发队列消息
查看>>
Spring Boot Unregistering JMX-exposed beans on shutdown
查看>>
poi 导入导出的api说明(大全)
查看>>
说说自己对RESTful API的理解s
查看>>
Mono for Android 优势与劣势
查看>>
将图片转成base64字符串并在JSP页面显示的Java代码
查看>>
js 面试题
查看>>
sqoop数据迁移(基于Hadoop和关系数据库服务器之间传送数据)
查看>>