问题: 一个已知的字符数组,把里面多余的空格去掉,得到一个新的字符数组,如{a, , ,b,c, , , ,d}变成{a, b,c, ,d}
要求: 不能使用临时数组,时间复杂度为O(n)
#include <iostream>
#include <string>
using namespace std;
#include <string>
using namespace std;
void fun2(char* cArr)
{
int iSpaceCounter = 0;
int iSpaceMarker = -1;
int iNotSpaceMarker = -1;
int iNotSpace = -1;
bool bMeetNotSpace = false;
for(int i = 0; i<strlen(cArr); ++i)
{
if(cArr[i] == ' ')
{
++iSpaceCounter;
if(iSpaceCounter == 2 && bMeetNotSpace)
{
iSpaceMarker = i;
}
else if(i == 0)
{
iSpaceMarker = 0;
}
}
else
{
if(iSpaceCounter > 1 || !bMeetNotSpace)
{
char temp = cArr[i];
cArr[i] = cArr[iSpaceMarker];
cArr[iSpaceMarker] = temp;
iNotSpace = iSpaceMarker;
iSpaceCounter -= 2;
if(iSpaceCounter < 0)
{
iSpaceCounter = 0;
}
iSpaceMarker += 2;
}
else
{
iNotSpace = i;
}
bMeetNotSpace = true;
}
}
cArr[iNotSpace+1] = '\0';
}
int main(int argc, char *args[])
{
char* cTar = NULL;
char* cTemp = " a b c";
char* cArr = new char[];
strcpy(cArr,cTemp);
fun2(cArr);
}