当从前到后出现覆盖情况时,请考虑从后往前!!!

替换空格

http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423

调用系统函数:s.replace()

创建新的字符串,遇到空格时追加"%20"

原地修改,从后往前,需要首先知道空格的个数。

    /**
     * 将一个字符串中的每个空格替换成“%20”
     * @param str 字符串
     * @return 替换后的字符串
     */

    public String replaceSpace(StringBuffer str) {
        int numOfSpace=0;
        int originLength= str.length();
        for(int i=0;i<originLength;i++){
            if(str.charAt(i)==' '){
                numOfSpace++;
            }
        }
        int newLength=originLength+numOfSpace*2;
        str.setLength(newLength);
        for(int i=originLength-1,j=newLength-1;i>=0&&j>=i;i--){
            char c=str.charAt(i);
            if(c==' '){
                str.setCharAt(j--,'0');
                str.setCharAt(j--,'2');
                str.setCharAt(j--,'%');
            }else {
                str.setCharAt(j--,c);
            }
        }
        return str.toString();
    }

大佬的图解,地址为:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-ji-jian-qing-xi-tu-/
图片说明

全部评论

相关推荐

2024-12-23 06:50
门头沟学院 Java
给点吧求求了:3点发的帖子,害怕😰
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务