1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
/****************************************************************************************** ******************************************************************************************* Chapter 1 Arrays and Strings * Replace all spaces in a string with '%20' By: Hamed Kiani (July 16, 2015) ****************************************************************************************** ******************************************************************************************/ #include<iostream> #include<cstring> using namespace std; // Replace inplace , time: O(n), additional space: O(1) void replace_space_with_20(char *str) { // return if str is NULL if (!str) return; // get the length of the str and the number of spaces int l = 0, nos = 0; // Q:how to write with a for loop? while (str[l] != '\0') { if (str[l] == ' ') nos++; l++; } cout << "the length of str is " << l << " with " << nos << " spaces " << endl; // the length of the new string, why not (nos*3)? ;-) int newl = (nos*2) + l; cout << " the new length is : " << newl << endl; // extend the original str to have the new length // Q: why newl--? str[newl--] = '\0'; l--; while(newl >= 0) { if (str[l] == ' ') { str[newl--] = '0'; str[newl--] = '2'; str[newl--] = '%'; l--; } else str[newl--] = str[l--]; } } // Q: how can you write the above function using additional buffer? // how about the time and space complexity? // Test it! int main() { char str[] = {"replace the spaces with 20% !"}; cout << "original str: " << str << "with the length of "<< strlen(str) << endl; replace_space_with_20(str); cout << "the new str: " << str << "with the length of "<< strlen(str) << endl; return 0; } |
2 Comments
hamed
7/15/2015 08:25:35 pm
the comment part works!
Reply
Leave a Reply. |
A place to practice the coding interview.
AuthorHamed Kiani Categories
All
Archives |