151. Reverse Words in a String 翻转字符串中的单词
2016-07-30 18:15
302 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
解答:
进行两次翻转操作,先对每个单词进行翻转,再对整个字符串进行翻转
这里的测试用例同时要求,去掉字符串前后的空字符,同时单词间若包含多个空字符,则只留一个空字符进行单词间的相隔即可。
class Solution {
public:
void rever(string& s, int begin, int end){
if(s.size() <= 1) return;
int b = begin, e = end;
while(b < e){
char t = s[b];
s[b] = s[e];
s[e] = t;
b++;
e--;
}
}
void reverseWords(string &s) {
if(s.size() <= 0) return;
int len = s.size();
int begin = 0;
int end = 0;
int index = 0;
int count = 0;
while(index < len){
while(index < len && s[index] == ' ') index++;
if(index == s.size())
break;
if(count) s[end++] = ' ';
begin = end;
while(index < len && s[index] != ' '){
s[end++] = s[index++];
}
rever(s, begin, end - 1);
count++;
}
s.resize(end); //这句话很重要
rever(s, 0, end-1);
}
};
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
解答:
进行两次翻转操作,先对每个单词进行翻转,再对整个字符串进行翻转
这里的测试用例同时要求,去掉字符串前后的空字符,同时单词间若包含多个空字符,则只留一个空字符进行单词间的相隔即可。
class Solution {
public:
void rever(string& s, int begin, int end){
if(s.size() <= 1) return;
int b = begin, e = end;
while(b < e){
char t = s[b];
s[b] = s[e];
s[e] = t;
b++;
e--;
}
}
void reverseWords(string &s) {
if(s.size() <= 0) return;
int len = s.size();
int begin = 0;
int end = 0;
int index = 0;
int count = 0;
while(index < len){
while(index < len && s[index] == ' ') index++;
if(index == s.size())
break;
if(count) s[end++] = ' ';
begin = end;
while(index < len && s[index] != ' '){
s[end++] = s[index++];
}
rever(s, begin, end - 1);
count++;
}
s.resize(end); //这句话很重要
rever(s, 0, end-1);
}
};
相关文章推荐
- 字符串翻转和单词倒转
- 算法(字符串移动,单词翻转)
- 字符串翻转 保持内部单词顺序【2012去哪儿网笔试最后一题】
- JAVA: 翻转单词 VS 左旋转字符串
- 字符串中单词的翻转(二)
- 剑指offer之面试题42翻转单词顺序VS左旋转字符串
- 剑指offer解题报告(Java版)——翻转单词顺序 左旋字符串 42
- 翻转子串 假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
- 剑指offer——翻转单词顺序VS左旋转字符串
- 以单词为单位翻转一个字符串
- [LeetCode]45. Reverse Words in a String按单词翻转字符串
- 剑指offer 42. 翻转单词顺序VS左旋转字符串
- 面试题42:翻转单词顺序VS左旋转字符串
- 剑指Offer之 - 翻转单词顺序 VS 左旋转字符串
- 将字符串中的单词翻转
- 翻转字符串中的单词
- 字符串中单词翻转实现
- 翻转单词顺序 VS 左旋转字符串43
- C语言左旋转字符串与翻转字符串中单词顺序的方法
- 翻转单词顺序VS左旋转字符串