Given an input string, reverse the string word by word.

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

Have you met this question in a real interview?

 
 
Clarification

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

题意

给定一个字符串,逐个翻转字符串中的每个单词。

 

说明

  • 单词的构成:无空格字母构成一个单词
  • 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
  • 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个

解法一:

 class Solution {
/**
* @param s : A string
* @return : A string
*/
public:
string reverseWords(string s) {
string ss;
int i = s.length() - ;
while (i >= ) {
while (i >= && s[i] == ' ') {
i--;
} if (i < ) {
break;
} if (ss.length() != ) {
ss.push_back(' ');
} string temp ;
for (; i >= && s[i] != ' '; i--) {
temp.push_back(s[i]);
} reverse(temp.begin(),temp.end()); ss.append(temp);
} return ss;
}
};

1、从后向前行进,如果为空格,则下标就递减,这是为了过滤最后面的那些空格。

2、遇到非空格就放到temp中,然后再翻转放入ss中

3、下一次再进入循环,还是过滤多余的空格,然后如果不是第一次进入循环就需要补充一个空格进来,再重复上面的过程即可

解法二:

 class Solution {
/**
* @param s : A string
* @return : A string
*/
public:
string reverseWords(string s) {
int storeIndex = , n = s.size(); reverse(s.begin(), s.end()); for (int i = ; i < n; ++i) {
if (s[i] != ' ') {
if (storeIndex != ) {
s[storeIndex++] = ' ';
} int j = i;
while (j < n && s[j] != ' ') {
s[storeIndex++] = s[j++];
} reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex); i = j;
}
}
s.resize(storeIndex); return s;
}
};

先整个字符串整体翻转一次,然后再分别翻转每一个单词(或者先分别翻转每一个单词,然后再整个字符串整体翻转一次),此时就能得到我们需要的结果了。那么这里我们需要定义一些变量来辅助我们解题,storeIndex表示当前存储到的位置,n为字符串的长度。我们先给整个字符串反转一下,然后我们开始循环,遇到空格直接跳过,如果是非空格字符,我们此时看storeIndex是否为0,为0的话表示第一个单词,不用增加空格;如果不为0,说明不是第一个单词,需要在单词中间加一个空格,然后我们要找到下一个单词的结束位置我们用一个while循环来找下一个为空格的位置,在此过程中继续覆盖原字符串,找到结束位置了,下面就来翻转这个单词,然后更新i为结尾位置,最后遍历结束,我们剪裁原字符串到storeIndex位置,就可以得到我们需要的结果。

参考@grandyang 的代码

解法三:

 class Solution {
/**
* @param s : A string
* @return : A string
*/
public:
string reverseWords(string s) {
istringstream is(s);
string tmp;
is >> s;
while (is >> tmp) {
s = tmp + " " + s;
}
if (!s.empty() && s[] == ' ') {
s = "";
} return s;
}
};

先把字符串装载入字符串流中,然后定义一个临时变量tmp,然后把第一个单词赋给s,这里需要注意的是,如果含有非空格字符,那么每次>>操作就会提取连在一起的非空格字符,那么我们每次将其加在s前面即可;如果原字符串为空,那么就不会进入while循环;如果原字符串为许多空格字符连在一起,那么第一个>>操作就会提取出这些空格字符放入s中,然后不进入while循环,这时候我们只要判断一下s的首字符是否为空格字符,是的话就将s清空即可。

参考@Zhoujingjin 的代码

解法四:

 class Solution {
/**
* @param s : A string
* @return : A string
*/
public:
string reverseWords(string s) {
istringstream is(s);
s = "";
string t = ""; while (getline(is, t, ' ')) {
if (t.empty()) {
continue;
}
s = (s.empty() ? t : (t + " " + s));
} return s;
}
};

使用getline来做,第三个参数是设定分隔字符,我们用空格字符来分隔,这个跟上面的>>操作是有不同的,每次只能过一个空格字符,如果有多个空格字符连在一起,那么t会赋值为空字符串,所以我们在处理t的时候首先要判断其是否为空,是的话直接跳过。

参考@grandyang 的代码

53. Reverse Words in a String【easy】的更多相关文章

  1. 345. Reverse Vowels of a String【easy】

    345. Reverse Vowels of a String[easy] Write a function that takes a string as input and reverse only ...

  2. 345. Reverse Vowels of a String【Easy】【双指针-反转字符串中的元音字符】

    Write a function that takes a string as input and reverse only the vowels of a string. Example 1: In ...

  3. 344. Reverse String【easy】

    344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...

  4. 557. Reverse Words in a String III【easy】

    557. Reverse Words in a String III[easy] Given a string, you need to reverse the order of characters ...

  5. 206. Reverse Linked List【easy】

    206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...

  6. 606. Construct String from Binary Tree 【easy】

    606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...

  7. 189. Rotate Array【easy】

    189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...

  8. 551. Student Attendance Record I【easy】

    551. Student Attendance Record I[easy] You are given a string representing an attendance record for ...

  9. 383. Ransom Note【easy】

    383. Ransom Note[easy] Given an arbitrary ransom note string and another string containing letters f ...

随机推荐

  1. IIS7 win7 x64 MVC部署

    .net4.5已经装好,mvc4setup也装了,启动IIS后打开网页还是不能正常显示页面,404错误 最后发现把win7升级到SP1就正常了,具体是那个补丁修复的就不知道了

  2. PhD Positions opening at University of Nevada, Reno (Wireless Networking / Cognitive Radio / Wireless Security)

    PhD Positions opening at University of Nevada, RenoDept. of Computer Science and Engineering Researc ...

  3. [Android 新特性] 改进明显 Android 4.4系统新特性解析

    Android 4.3发布半年之后,Android 4.4随着新一代Nexus5一起出现在了用户的面前,命名为从之前的Jelly Bean(果冻豆)换成了KitKat(奇巧).这个新系统究竟都有怎样的 ...

  4. 使用 Kafka 和 Spark Streaming 构建实时数据处理系统(转)

    原文链接:http://www.ibm.com/developerworks/cn/opensource/os-cn-spark-practice2/index.html?ca=drs-&ut ...

  5. onehot的好处,还是可以看看的

    https://www.jqr.com/article/000243 一句话概括:one hot编码是将类别变量转换为机器学习算法易于利用的一种形式的过程. 类别值是分配给数据集中条目的数值编号. s ...

  6. JS 与Flex交互:html中的js 与flex中的actionScript通信

    Flex与JavaScript交互的问题,这里和大家分享一下,主要包括Flex调用JavaScript中的函数和JavaScript调用Flex中的函数两大部分内容. Flex 与JavaScript ...

  7. iFrame的妙用

    (作者: Glen,返利网资深工程师,曾在EA等公司任职) 最近工作有个在项目-布兜收藏夹.简言之就是将喜欢的图片收藏到布兜页面上来,这其中用到了很多关于iframe的方面,总结如下: 1. 作为弹出 ...

  8. C#实现两个数据库之间的数据上报

    用VS2008实现本地数据库上传数据到远程数据.数据能够是一个表,或一个表的部分数据.或查询数据.或数据编辑后上传. 其他VS版本号.复制当中代码就能够.未使用其他不论什么插件.有具体凝视. 单独页面 ...

  9. 【php】Apache无法自己主动跳转却显示文件夹与php无法连接mysql数据库的解决方式

    一.Apache无法自己主动跳转却显示文件夹 Apache无法自己主动跳转却显示文件夹这是由于Apacheserver下conf/httpd.conf没有配置好,其默认是不跳转,直接显示文件夹 首先, ...

  10. 15个重要Python面试题 测测你适不适合做Python?

    http://nooverfit.com/wp/15%E4%B8%AA%E9%87%8D%E8%A6%81python%E9%9D%A2%E8%AF%95%E9%A2%98-%E6%B5%8B%E6% ...