Skip to content

Instantly share code, notes, and snippets.

@monkerek
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkerek/61cbc179c97c5d263beb to your computer and use it in GitHub Desktop.
Save monkerek/61cbc179c97c5d263beb to your computer and use it in GitHub Desktop.
1.4 Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
// first find the index where the actual string ends
// then calculate the number of spaces to be converted to assure the length of the result string
// use two pointers, one pointing to the end of the former string, the other pointing to the end of the result string
// then move pointers backwards to convert spaces one by one, and this can be done in-place.
// time complexity: O(n)
// space complexity: O(1)
class Solution
{
public:
void ReplaceSpace(char *str)
{
if(str == NULL)
return;
unsigned int len = strlen(str);
int front = len - 1, end = front;
while(str[front] == ' ') // find the index of the end of the actual string(get rid of tailing spaces)
front--;
int index = front, count = 0;
while(index >= 0)
if(str[index--] == ' ')
count++; // count spaces to be converted;
end = front + count * 2; // the len(result string) = len(former string) + #spaces * 2
str[end + 1] = '\0'; // tailor the result string
while(front >= 0 && end >= 0) // trace backwards
{
if(str[front] == ' ')
{
str[end--] = '0';
str[end--] = '2';
str[end--] = '%';
} // convert spaces
else
str[end--] = str[front];
// move non-space characters
front--;
}
}
};
@habina
Copy link

habina commented Jun 17, 2014

After I run and debug it, I realize how line 30 - 43 work. Good work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment