跳过正文
  1. Posts/

[151] Reverse Words in a String

·1 分钟·
目录

题目:Reverse Words in a String
#

Given an input string s, reverse the string word by word. For example, given s = “the sky is blue”, return “blue is sky the”.

题意:
#

题意很明确,将字符串中的单词进行翻转,形成新的字符串。但是这其中有几个问题我们需要思考(参考leetCode官方CleanCodeBook):

Q: What constitutes a word? A: A sequence of non-space characters constitutes a word.

Q: Does tab or newline character count as space characters? A: Assume the input does not contain any tabs or newline characters.

Q: Could the input string contain leading or trailing spaces? A: Yes. However, your reversed string should not contain leading or trailing spaces.

Q: How about multiple spaces between two words? A: Reduce them to a single space in the reversed string.

解法:
#

class Solution {
public:
	void reverseWords(std::string &s) {
		
	   std::string reversed("");
		int j = s.length();

		for (int i = s.length() - 1; i >= 0; --i) {
			if(s.at(i) == ' ') j = i;
			else if (i == 0 || s.at(i - 1) == ' ') {
				if (reversed.length() != 0) reversed += ' ';
				reversed += s.substr(i, j - i);
			}
		}
		s = reversed;
	}
}

相关文章

Two Sum

·3 分钟
本文主要包括 leetCode 题集里的两个题目,Two Sum1 和 Two Sum2 题目1: 1. Two Sum 1 # Given an array of integers, find two numbers such that they add up to a specific target number.

[152] Maximum Product Subarray

·1 分钟
题目: # Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.

关于Lambda的一点梳理

·3 分钟
关于C++11的新特性,最近接触比较多的就是关于thread的部分,还有就是Lambda表达式,今天主要针对Lambda的用法进行一定的阐述和汇总(参考链接在文章下方,向大师致敬!),同时给自己梳理下知识点,加深印象。

scala Day2

·5 分钟
因为这几天在学习Coursera公开课Principles of Reactive Programming ,因为之前木有木有注意到需要对至少一门函数式编程语言solid foundation,因此只能临时抱佛脚,恰好手头有一本七周七语言这本书一直木有看,借着这个课程的督促把这本书翻看下,当然内容仅包括Scala这一章,今天看到第二天的内容,重头戏是Collection。这篇blog主要记录关于这次自习题的解答。

博客之旅

·1 分钟
如果你不给自己烦恼,别人也永远不可能给你烦恼,因为你自己的内心,你放不下 其实写博客一直在我的ToDoList上,不过放的时间有点久。我就是这样一个人,想干的太多,做到的却相当少。因此写这个博客的目的也是想督促自己前行,记录生活点滴的同时也能够让自己对生活有一些感悟。告诉自己,世界很大,千万不要局限在自己的小圈圈里无法自拔!