题目链接

牛客网

题目描述

将一个字符串中的空格替换成 “%20”。

  1. Input:
  2. "A B"
  3. Output:
  4. "A%20B"


解题思路( 考虑从右向左,遇到空格,就填充“20%“,否则将原字符移动应该呆的位置。)

① 在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),所以当遍历到一个空格时,需要在尾部填充两个任意字符。
② 令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
③ 当 P2 遇到 P1 时(P2 <= P1),或者遍历结束(P1 < 0),退出。
image.png

  1. public String replaceSpace(StringBuffer str) {
  2. int P1 = str.length() - 1;
  3. for (int i = 0; i <= P1; i++)
  4. if (str.charAt(i) == ' ')
  5. str.append(" ");
  6. int P2 = str.length() - 1;
  7. while (P1 >= 0 && P2 > P1) {
  8. char c = str.charAt(P1--);
  9. if (c == ' ') {
  10. str.setCharAt(P2--, '0');
  11. str.setCharAt(P2--, '2');
  12. str.setCharAt(P2--, '%');
  13. } else {
  14. str.setCharAt(P2--, c);
  15. }
  16. }
  17. return str.toString();
  18. }
  19. //我的代码
  20. class Solution {
  21. public:
  22. void replaceSpace(char *str,int length) {
  23. if(str==nullptr||length<=0)
  24. return;
  25. int space = 0,index;
  26. for(int i=0;i<length;i++){
  27. if(*(str+i)==' ')
  28. ++space;
  29. }
  30. index = length + 2*space;
  31. *(str+index) = '\0';
  32. index--;
  33. length--;
  34. while(length>=0){
  35. if(*(str+length)==' '){
  36. *(str+index) = '0';
  37. *(str+index-1) = '2';
  38. *(str+index-2) = '%';
  39. index -= 2;
  40. }else{
  41. *(str+index) = *(str+length);
  42. }
  43. index--;
  44. length--;
  45. }
  46. }
  47. };
  48. // 利用C++特性
  49. class Solution {
  50. public:
  51. string replaceSpace(string s) {
  52. int len = s.length();
  53. if(len==0)
  54. return s;
  55. string res;
  56. for(const char c:s){
  57. if(c==' '){
  58. res += "%20";
  59. }else{
  60. res += c;
  61. }
  62. }
  63. return res;
  64. }
  65. };
  • 时间复杂度:O(length) 只遍历了一遍字符串
  • 空间复杂度:O(1) 没有开辟空间