• 实现替换空格


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

    【思路】一开始有人惯性思维,从前向后进行替换,也不可不行,但会发现如果有两个空格,那么“Happy”会被移动两次,这就会使效率变差,能不能移动一次就行呢?打破惯性思维,从后向前移动就好了!确定长度后直接将“Happy”移到最后,只需要一次!

    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            int count = 0;
            for(int i =0;i < length; i++){
                if(str[i] == ' ')
                    count++;
            }
            for(int i = length; i >= 0; i--){
                if(str[i] != ' ')
                {
                    str[i + 2*count] = str[i];
                }
                else{
                    str[i+2*count] = '0';
                    str[i+2*count-1] = '2';
                    str[i+2*count-2] = '%';
                    count--;
                }
            }
        }
    };
  • 相关阅读:
    网页定位导航
    position元素的定位
    节点属性
    css控制换行,断词
    css隐藏多余文字显示...
    重绘和回流
    CSS属性书写顺序
    模拟select
    常用html标签
    clientHeight、scrollHeight和offsetHeight基本用法
  • 原文地址:https://www.cnblogs.com/zhudingtop/p/11291257.html
Copyright © 2020-2023  润新知