//题目:将字符串中的所有空格去掉,要求时间复杂度O(n),空间复杂度O(1)
#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
int delSpace(char *pStr)
{
assert(pStr);
char *pTmp = pStr;
int count = 0;
while (*pTmp != '\0')
{
while (*pTmp == ' ')
{
count++;
pTmp++;
}
*pStr = *pTmp;
if (*pStr == '\0')
{
cout << "空格的个数: " << count << endl;
return count;
}
else
{
pStr++;
}
pTmp++;
}
*pStr = '\0';
cout << "空格的个数: " << count << endl;
return count;
}
int main()
{
//char str[]="helloworldxxyywhyabd"; //情况1
char str[] = " hello world xx yy abd";//情况2
cout << str << " len:" << strlen(str) << endl;
delSpace(str);
cout << str << " len:" << strlen(str) << endl;
system("pause");
return 0;
}
解析:
使用双指针指向该字符串,在此例中为pStr和pTmp,pStr用于记录当前写入的位置,pTmp则用于遍历整个字符串。