zoukankan      html  css  js  c++  java
  • 2、替换空格

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

    ============Python============

    # -*- coding:utf-8 -*-
    class Solution:
        # s 源字符串
        def replaceSpace(self, s):
            # write code here
            res = s.split(' ');
            ans = '';
            for i in range(len(res) - 1):
                ans += res[i]
                ans += '%20'
            ans += res[-1]
            return ans

    ================Java==============

    public class Solution {
        public String replaceSpace(StringBuffer str) {
            //遍历一遍字符串找出空格的数量
            if (str == null || str.length() < 0) {
                return null;
            }
            int spacenum = 0;  //计算空格数
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == ' ')
                    spacenum++;
            }
            int indexold = str.length() - 1;
            int newlength = str.length() + spacenum * 2;
            int indexnew = newlength - 1;
            str.setLength(newlength);
            for (;indexold>=0 && indexold<newlength; --indexold) {
                if (str.charAt(indexold) == ' '){
                    str.setCharAt(indexnew--, '0');
                    str.setCharAt(indexnew--, '2');
                    str.setCharAt(indexnew--, '%');
                } else {
                    str.setCharAt(indexnew--, str.charAt(indexold));
                }
            }
            return str.toString();
        }
    }
  • 相关阅读:
    浅谈最长上升子序列(LIS)
    浅谈树链剖分
    数字计数
    windy数
    骑士(树形dp)
    旅游规划
    皇宫看守
    k8s安装报错
    linux文件夹存储潜规则
    搭建覆盖率测试环境
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13537810.html
Copyright © 2011-2022 走看看