《Cracking the Coding Interview》——第1章:数组和字符串——题目4

2014-03-18 01:36

题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。

解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。

代码:

 1 // 1.4 Write a method to replace all spaces in a string with '%20'.

 2 // do it in-place and backward.

 3 #include <cstdio>

 4 #include <cstring>

 5 using namespace std;

 6 

 7 class Solution {

 8 public:

 9     void replaceSpace(char *str) {

10         if (nullptr == str) {

11             return;

12         }

13 

14         int i, j;

15         int len = (int)strlen(str);

16         int cc = 0;

17         for (i = 0; i < len; ++i) {

18             if (str[i] == ' ') {

19                 ++cc;

20             }

21         }

22 

23         int tc = 0;

24         for (i = len - 1; i >= 0; --i) {

25             if (str[i] == ' ') {

26                 ++tc;

27             } else {

28                 break;

29             }

30         }

31         cc -= tc;

32 

33         j = i;

34         i = cc;

35         while (j >= 0) {

36             if (str[j] == ' ') {

37                 --cc;

38                 str[j + 2 * cc] = '%';

39                 str[j + 2 * cc + 1] = '2';

40                 str[j + 2 * cc + 2] = '0';

41             } else {

42                 str[j + 2 * cc] = str[j];

43             }

44             --j;

45         }

46         if (2 * i > tc) {

47             str[len - tc + 2 * i] = 0;

48         }

49     }

50 };

51 

52 int main()

53 {

54     char str[1000];

55     Solution sol;

56 

57     while (gets(str) != nullptr) {

58          sol.replaceSpace(str);

59         puts(str);

60     }

61 

62     return 0;

63 }

 

你可能感兴趣的:(interview)