这是华为内部的一个OJ题目
对字符串中的所有单词进行倒排。
说明:
1、每个单词是以26个大写或小写英文字母构成;
2、'-‘做为单词连接符使用时,视为单词的一部分,例如“aa-bb”是一个单词;但连续出现2个’-’及以上时视为单词间隔符,如“aa--bb”中的“--”视为间隔符,是2个单词“aa”和“bb”;
3、非构成单词的字符均视为单词间隔符;
4、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;
5、每个单词最长20个字母;
实现代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int Converse(char* pInput, char* pOutput);
int main()
{
char *pInput = "what is the-boy that wear--blue pants$and wear-red hat";
char *pOutput = new char(100);
Converse(pInput,pOutput);
cout<<pOutput<<endl;
return 0;
}
int Converse(char* pInput, char* pOutput)
{
int i, inputIndex, outputIndex, front, end, wordLen;
outputIndex = 0;
inputIndex = strlen(pInput) - 1;
while(inputIndex >= 0)
{
wordLen = 1;
front = inputIndex - 1;
end = inputIndex;
//能连续成为一个单词的条件
while((front >= 0) && ((isalpha(pInput[inputIndex])) || (isalpha(pInput[front]) && pInput[inputIndex] == '-')))
{
inputIndex--;
front--;
wordLen++;
}
if (wordLen > 20)
{
return -1;
}
if(inputIndex != 0)
{
for(i = inputIndex + 1; i <= end;i++)
{
pOutput[outputIndex++] = pInput[i];
}
pOutput[outputIndex++] = ' ';
}
else
{
for(i = inputIndex;i <= end;i++)
pOutput[outputIndex++] = pInput[i];
break;
}
if(pInput[inputIndex] == '-' && pInput[front] == '-')
inputIndex = inputIndex - 2;
else
inputIndex--;
}
pOutput[outputIndex++] = '\0';
return 0;
}