Saturday, September 1, 2012

Remove all two zeros in the given string. Example: a3409jd00dk000d Output: a3409jddk000d Note: If there are less/more than two zeros consecutive, it should not be replaced.

#include<iostream>
#include <string.h>
using namespace std;
 
void removeDoubleZeros(char* src)
{
int len = strlen(src);
 
 
int idxSrc = 0;
int idxDest = 0;
while (idxSrc + 1 < len)
{
if(src[idxSrc]=='0'&& src[idxSrc+1]== '0')
{
 if(
 ((idxSrc - 1 >= 0 && src[idxSrc - 1]!= '0') 
   || idxSrc - 1 < 0) &&
 ((idxSrc + 2 < len && src[idxSrc + 2]!= '0')
  || idxSrc + 2 >= len)
)
 
{
idxSrc += 2;
}
else
src[idxDest++] = src[idxSrc++];
}
else
{
src[idxDest++] = src[idxSrc++];
}
}
 
 
src[idxDest++] = src[idxSrc];
src[idxDest] = 0;
};
 
 
int main()
{
char src[] = "a3409jd00dk000d";
 
 
removeDoubleZeros(src);
printf("%s", src);
 
return 0;
}
 
Time Complexity O(N) where N is length 
of string
Space Complexity O(1)
Run Here http://ideone.com/1p3Sb

No comments :