您的位置:首页 > 编程语言 > C语言/C++

【C语言】 LeetCode 151. Reverse Words in a String

2017-01-06 13:54 519 查看

题目:

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

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

Update (2015-02-12):

For C programmers: Try to solve it in-place in O(1) space.

解答:

void reverse(char * s, int first, int last)
{
while (first < last)
{
char tmp = s[first];
s[first++] = s[last];
s[last--] = tmp;
}
}

void reverseWords(char *s) {
int last = 0, now = 0;
//翻转每个单词,同时翻转整个字符串,则对应单词拼写正确
while (s[now])
{
while (s[now] == ' ') now++;
last = now;
while (s[now] != ' ' && s[now] != '\0') now++;
reverse(s, last, now - 1);
}
reverse(s, 0, now - 1);
last = 0;

//删除多余的空格
for (int i = 0; i < now; i++)
{
if (!isblank(s[i]) || (last && s[last - 1] != s[i]))
s[last++] = s[i];
}
s[last] = 0;
if (last && s[last - 1] == ' ')
s[last - 1] = 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: