牛客网剑指offer题目(三、 替换空格)


前言

提示:本系列所有相关代码都以C++为编程语言进行讲解。且格式采用牛客网的给定格式。


题目

请实现一个函数,将一个字符串s中的每个空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

数据范围:0≤len(s)≤1000 。 保证字符串中的字符为大写英文字母、小写英文字母和空格中的一种。

一、新建一个空字符串,利用string的+=方法,进行字符串的替换

创建一个空字符串,并依次遍历s,如果不是空格,则将s复制给空字符串,否则+=‘%20’

class Solution {
          
   
public:
    string replaceSpace(string s) {
          
   
        // write code here
        string res = "";
        for(int i = 0 ; i < s.length() ; i++)
        {
          
   
            if(s.at(i) !=  ) 
            {
          
   
                res += s.at(i);
            }
            else res += "%20";
        }
        return res;
    }
};

二、利用string类型的insert()函数对空格位置进行插入,从而达到替换的目的

遍历s,如果遇到空格则将其替换为‘%’,并在其后面利用insert()函数插入‘20’

class Solution {
          
   
public:
    string replaceSpace(string s) {
          
   
        // write code here
        for(int i = 0 ; i < s.length() ; i++)
        {
          
   
            if(s.at(i) ==  ) 
            {
          
   
                s.at(i) = %;
                s.insert(i+1, "20");
            }
        }
        return s;
    }
};

三、利用find_last_of()和replace()进行空格寻找和替换

利用find_last_of()函数进行空格查找,如果没找的则返回-1,如果找到返回空格的位置,并利用replace()函数,进行替换

class Solution {
          
   
public:
    string replaceSpace(string s) {
          
   
        // write code here
        int len = s.length(), i = 0;
        for(i = 0; i< len; i++)
        {
          
   
            int index = s.find_last_of( , -1);
            if (index == -1)
                return s;
            s.replace(index, 1, "%20");
        }
        return s;
    }
};
经验分享 程序员 微信小程序 职场和发展