题目

请实现一个函数,把字符串 s 中的每个空格替换成"%20"

示例 1:

  1. 输入:s = "We are happy."
  2. 输出:"We%20are%20happy."

限制:

  • 0 <= s 的长度 <= 10000

    解题方法

    双指针

    遍历数组,通过双指针记录非空格段字符串。

    1. class Solution {
    2. public:
    3. string replaceSpace(string s) {
    4. int n = s.size();
    5. int slow = 0, fast = 0;
    6. string out;
    7. while(fast<n) {
    8. if(s[fast]==' '){
    9. out = out + s.substr(slow, fast-slow) + "%20";
    10. slow = fast+1;
    11. }
    12. fast++;
    13. }
    14. out = out + s.substr(slow, fast-slow);
    15. return out;
    16. }
    17. };

    遍历数组

    1. class Solution {
    2. public:
    3. string replaceSpace(string s) {
    4. string out;
    5. for(auto i:s) {
    6. if(i==' ') out+="%20";
    7. else out+=i;
    8. }
    9. return out;
    10. }
    11. };

    双指针反向修改数组

    先遍历数组,确定修改后的大小。

    1. class Solution {
    2. public:
    3. string replaceSpace(string s) {
    4. int count = 0;
    5. int n = s.size();
    6. for(auto i:s) {
    7. if(i==' ') count++;
    8. }
    9. int new_n = n+count*2;
    10. int i = n-1;
    11. int j = new_n-1;
    12. s.resize(new_n);
    13. while(i>=0){
    14. if(s[i]==' ') {
    15. s[j] = '0';
    16. s[j-1] = '2';
    17. s[j-2] = '%';
    18. j-=2;
    19. }
    20. else s[j] = s[i];
    21. i--;j--;
    22. }
    23. return s;
    24. }
    25. };