题解 | #替换空格#

替换空格

https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68

#include <iostream>
#include <string>
using namespace std; 
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    string replaceSpace(string s) {
        // write code here
        int length = s.length();
        char* array = new char[length*3];
        int index=0;
        for(int i=0;i<length;i++){
            if(s[i]==' '){
                array[index]='%';
                index++;
                array[index]='2';
                index++;
                array[index]='0';
                index++;
            }
            else {
                array[index]=s[i];
                index++;
            }
        }
        string output(array);
        cout <<output<< endl;
        delete[] array;
        return output;

    }
};

在堆上新建一个三倍输入大小的动态字符数组array,然后遍历输入字符串,判断当前字符是否为空格,若是, 则将array索引为index,index+1, index+2的值赋值为%,2,0,若不是空格,则将array[index]赋值为此字符,最后清除array内存。

全部评论

相关推荐

未来十年java最好的一年:为什么不要JAVA,为什么
点赞 评论 收藏
分享
等华子还是签贝壳?
投递贝壳找房等公司10个岗位 >
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务