zoukankan      html  css  js  c++  java
  • 剑指offer系列——2.替换空格

    Q:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
    C:时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 32M,其他语言64M
    T:
    我这是开辟了一个新的字符串帮助,实际上如果字符串较大就并不好。
    讨论区主要方法:
    1.从后往前插入,这样不需要另辟新的空间。

    void replaceSpace(char *str,int length) {
            int oldlen=0,newlen=0;
            while(str[oldlen]!='')
            {
                if(str[oldlen]==' ')
                    newlen+=2;
                newlen++,oldlen++;
            }
           //此时str[i]指向,而对于字符串来说结尾必须有
            newlen++;//给''占一个空间
            str[newlen--]='';
            while(newlen>oldlen&&oldlen>=0)
            {
                if(str[oldlen]==' ')
                {
                    str[newlen--]='0';
                    str[newlen--]='2';
                    str[newlen--]='%';
                }
                else
                    str[newlen--]=str[oldlen];
                oldlen--;
            }
    }
    

    2.把字符串转成string形式,再转回来。这样真的方便很多。但说实话,这样需要很强的string使用能力。

    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            string s(str);
            int i=0;
            while((i=s.find(' ',i))>-1){
                s.erase(i,1);
                s.insert(i,"%20");
                 
            }
            auto ret=s.c_str();
            strcpy(str,ret);
        }
    };
    

    3.如果可以……实际上直接用replace,方便快捷哈哈哈哈。

  • 相关阅读:
    Codeforces Ilya and Matrix
    poj 1308 Is It A Tree?
    Codeforces Sereja and Array
    poj 1041 John's trip
    Codeforces Continued Fractions
    WM_COPYDATA实现进程间数据通信
    虚拟机中安装ubuntu后,终端模式和图形模式切换
    IIS上配置运行cgi,php,aspx运行环境
    linux c main函数参数
    Linux网络编程入门 (转载)
  • 原文地址:https://www.cnblogs.com/xym4869/p/12237056.html
Copyright © 2011-2022 走看看