算法- 翻转句子中单词的顺序
2012-09-25 15:42
344 查看
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。
由于本题需要翻转句子,我们先颠倒句子中的所有字符。这时,不但翻转了句子中单词的顺序,而且单词内字符也被翻转了。我们再颠倒每个单词内的字符。由于单词内的字符被翻转两次,因此顺序仍然和输入时的顺序保持一致。
还是以上面的输入为例子。翻转“I am a student.”中所有字符得到“.tneduts a ma I”,再翻转每个单词中字符的顺序得到“students. a am I”,正是符合要求的输出。
参考代码:
View Code
#include
#include
using namespace std;
// 反转字符串
void Reverse(char *begin, char *end)
{
if (begin == NULL || end == NULL)
return;
char tmp;
while (begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
begin ++;
end --;
}
}
char* ReverseSentence(char* sentence)
{
if (sentence == NULL)
return NULL;
char *begin, *end;
begin = sentence;
end = sentence;
while (*end != '\0')
end ++;
end --;
// 先反转所有字符
Reverse(begin, end);
while (*begin != '\0')
{
end = begin;
while (*end != ' ' && *end != '\0')
end ++;
end --;
Reverse(begin, end);
if (*(end + 1) == ' ')
begin = end + 2;
else
begin = end + 1;
}
return sentence;
}
例如输入“I am a student.”,则输出“student. a am I”。
由于本题需要翻转句子,我们先颠倒句子中的所有字符。这时,不但翻转了句子中单词的顺序,而且单词内字符也被翻转了。我们再颠倒每个单词内的字符。由于单词内的字符被翻转两次,因此顺序仍然和输入时的顺序保持一致。
还是以上面的输入为例子。翻转“I am a student.”中所有字符得到“.tneduts a ma I”,再翻转每个单词中字符的顺序得到“students. a am I”,正是符合要求的输出。
参考代码:
View Code
#include
#include
using namespace std;
// 反转字符串
void Reverse(char *begin, char *end)
{
if (begin == NULL || end == NULL)
return;
char tmp;
while (begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
begin ++;
end --;
}
}
char* ReverseSentence(char* sentence)
{
if (sentence == NULL)
return NULL;
char *begin, *end;
begin = sentence;
end = sentence;
while (*end != '\0')
end ++;
end --;
// 先反转所有字符
Reverse(begin, end);
while (*begin != '\0')
{
end = begin;
while (*end != ' ' && *end != '\0')
end ++;
end --;
Reverse(begin, end);
if (*(end + 1) == ' ')
begin = end + 2;
else
begin = end + 1;
}
return sentence;
}
相关文章推荐
- 程序员面试题精选100题(07)-翻转句子中单词的顺序[算法]
- 程序员面试50题(3)—翻转句子中单词的顺序[算法]
- 算法习题10:翻转句子中单词的顺序
- 微软算法100题10 翻转句子中单词的顺序
- [面试算法题重做]翻转句子中单词的顺序
- 翻转句子中单词的顺序[算法]
- 程序员面试题精选100题(07)-翻转句子中单词的顺序[算法]
- 算法讨论(六)--翻转句子中单词的顺序
- 微软算法100道题-----翻转句子中单词的顺序
- 【经典算法】:翻转句子中单词的顺序
- 程序员面试100题(算法)之翻转句子中单词的顺序
- 每日一道算法题5——翻转句子中单词的顺序
- 程序员面试题精选-翻转句子中单词的顺序[算法]
- 每天学习一算法系列(10)(输入一句英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开)
- 每天一算法(翻转句子中单词的顺序)
- 程序员面试题精选100题(07)-翻转句子中单词的顺序[算法]
- 10. 翻转句子中单词的顺序。
- 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不改变
- 翻转句子中单词的顺序
- 10.翻转句子中单词的顺序