53. Reverse Words in a String【easy】
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
- 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】的更多相关文章
- 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 ...
- 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 ...
- 344. Reverse String【easy】
344. Reverse String[easy] Write a function that takes a string as input and returns the string rever ...
- 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 ...
- 206. Reverse Linked List【easy】
206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...
- 606. Construct String from Binary Tree 【easy】
606. Construct String from Binary Tree [easy] You need to construct a string consists of parenthesis ...
- 189. Rotate Array【easy】
189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...
- 551. Student Attendance Record I【easy】
551. Student Attendance Record I[easy] You are given a string representing an attendance record for ...
- 383. Ransom Note【easy】
383. Ransom Note[easy] Given an arbitrary ransom note string and another string containing letters f ...
随机推荐
- java后台与jsp前台特殊字符处理(字符串编码与解码)
在后台与前台数据交互时如果有特殊字符就很容易出现问题,所以就需要对字符串进行编码传输,在获取后再进行解码: 1.Java后台进行编码与解码 URLEncoder.encode(str,"ut ...
- MyEclipse 如何最佳设置
摘自: http://blog.csdn.net/lifuxiangcaohui/article/details/8513561 MyEclipse 如何最佳设置 作为企业级开发最流行的工具,用Mye ...
- Event.RESIZE 的事件不触发
stage.scaleMode=StageScaleMode.NO_SCALE;(或者设置其他缩放模式,如EXACT_FIT等): 如果没有设置 stage的缩放模式的话, stage.addEv ...
- STL - Predicate - Binary Predicate(双参判断式)
Binary Predicate(双参判断式)的用途是:比较两个参数的特定属性 我们先建一个领域模型类: Person.h #ifndef _Domain_Models_Person_H_ #defi ...
- Cocos2d-x 处理双击事件的两种方法
在cocos2d-x的开发过程中有些时候也是需要用到双击的事件处理,那么由于在cocos2d-x中没有实现对双击的事件的处理,那么我们就需要自己用代码实现. 下面介绍两种方式实现双击事件的处理. (一 ...
- 从CM刷机过程和原理分析Android系统结构
前面101篇文章都是分析Android系统源代码,似乎不够接地气. 假设能让Android系统源代码在真实设备上跑跑看效果,那该多好.这不就是传说中的刷ROM吗?刷ROM这个话题是老罗曾经一直避免谈的 ...
- CentOS如何安装linux桌面?
CentOS如何安装linux桌面? 以前默认安装分centos没有图形界面,今天想用下, yum groupinstall "GNOME Desktop" "Graph ...
- hunnu11546:Sum of f(x)
Problem description 令f(x)为x的全部约数之和,x的约数即能够被x整除的数.如f(24)=1+2+3+4+6+8+12+24=60),求 f(l) + f(l + 1) + ...
- 如何知道TSQL语句已经运行了多久
如何知道TSQL语句已经运行了多久 ,) --millisecond per tick --如果datediff 函数导致溢出 把下面的millisecond改为second 毫秒改为秒 SELECT ...
- 18-spring学习-AOP深入操作
范例:定义一个参数拦截 package com.Spring.aop; import org.springframework.stereotype.Component; @Component publ ...