面试题38:翻转句子中单纯词的顺序,单词内字符的顺序不变

面试题38:翻转句子中单词的顺序,单词内字符的顺序不变

题目:给出一个英文句子,翻转句子中单词的顺序,单词内字符的顺序不变。
例如:"I am a student."输出"student. a am I"
思路:先翻转整个句子,然后翻转单词

代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;

//题目:给出一个英文句子,翻转句子中单词的顺序,单词内字符的顺序不变。
//例如:"I am a student."输出"student. a am I"
//思路:先翻转整个句子,然后翻转单词

//逆置长度为nLength的字符串str
void Reverse(char str[], int nLength)
{
	if (str == NULL || nLength == 0)
	{
		return;
	}	

	char temp = 'a';
	for (int i=0; i<nLength/2; i++)
	{
       temp = str[i];	  
	   str[i] = str[nLength-i-1];
	   str[nLength-i-1] = temp;
	}
}

void ReverseSentence(char str[])
{
	if (str == NULL)
	{
		return;
	}
	
	//翻转整个句子
	Reverse(str, strlen(str));
	cout << str << endl;

	int nIndex = 0;
	int nStart = 0;
	int nCount = 0;
	while (nIndex < (int)strlen(str) )
	{
		while (str[nIndex] == ' ')//对于字符串以若干空格符开始和中间有若干连续空格的情况
		{
			nIndex++;
		}

        nStart = nIndex;

		while (str[nIndex] != ' ' && nIndex < strlen(str))
		{
			nIndex++;
		    nCount++;		 
		}
        
		//翻转句子中的单词
		Reverse(str+nStart, nCount);
		nCount = 0;		
	}	
}

int _tmain(int argc, _TCHAR* argv[])
{
	//char str[] = "I am a student.";
	char str[] = "    I    am   a    student.   ";
	ReverseSentence(str);
	cout << str << endl;
	system("pause");
	return 0;
}

运行结果:

面试题38:翻转句子中单纯词的顺序,单词内字符的顺序不变

 

1楼Stanly7昨天 13:14
既然是句子,何不切开,然后翻转。比翻转整个再翻单词,不仅快还方便。你这样太麻烦了
Re: htyurencaotang昨天 13:44
回复Stanly7n貌似可行,有空我试试,谢谢!