天天看点

【C语言】 LeetCode 151. Reverse Words in a String题目:解答:

题目:

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;
}