美文网首页
剑指 Offer 05. 替换空格

剑指 Offer 05. 替换空格

作者: 7ccc099f4608 | 来源:发表于2021-03-07 15:14 被阅读0次

https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

image.png

(图片来源https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

日期 是否一次通过 comment
2021-03-07 0

 public String replaceSpace(String s) {
        if(s.isEmpty()) {
            return s;
        }

        int spaceN = 0;
        for(char v : s.toCharArray()) {  // 注意char、.toCharArray()
            if(v == ' ') {
                spaceN ++;
            }
        }

        char[] c = new char[s.length()+2*spaceN];
        int origIdx = s.length()-1, newIdx = s.length()+2*spaceN-1;
        while(origIdx >=0 && newIdx >=0) {
            if(s.charAt(origIdx) == ' ') {
                c[newIdx--] = '0';
                c[newIdx--] = '2';
                c[newIdx--] = '%';
                origIdx --;
            } else {
                c[newIdx--] = s.charAt(origIdx--);
            }

        }

        return new String(c);

    }

相关文章

网友评论

      本文标题:剑指 Offer 05. 替换空格

      本文链接:https://www.haomeiwen.com/subject/zkkyqltx.html