zoukankan      html  css  js  c++  java
  • Lc_剑指Offer05替换空格

    package com.leetcode.leetcode.licm;
    
    /**
     * @description: 剑指 Offer 05. 替换空格
     * 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
     * <p>
     * <p>
     * <p>
     * 示例 1:
     * <p>
     * 输入:s = "We are happy."
     * 输出:"We%20are%20happy."
     * <p>
     * <p>
     * 限制:
     * <p>
     * 0 <= s 的长度 <= 10000
     * @author: licm
     * @create: 2021-07-12 10:47
     **/
    public class Lc_剑指Offer05替换空格 {
        /**
         * * 第一步 检索当前字符串有多少个空格,然后进行扩容
         * <p>
         * 第二部 将空格从后向前替换,利用双指针
         *
         * @param s
         * @return
         */
        public static String replaceSpace(String s) {
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    count++;
                }
            }
    
            char[] charS = s.toCharArray();
            char[] newCharS = new char[charS.length + count * 2];
            for (int i = charS.length - 1; i >= 0; i--) {
                newCharS[i] = charS[i];
            }
    
            int left = charS.length - 1;
            int right = newCharS.length - 1;
           while(left<right) {
                if (newCharS[left] == ' ') {
                    newCharS[right] = '0';
                    newCharS[right - 1] = '2';
                    newCharS[right - 2] = '%';
                    right -= 2;
    
                } else {
                    newCharS[right] = newCharS[left];
                }
                left--;
                right--;
            }
            String newStr = new String(newCharS, 0, newCharS.length);
            return newStr;
        }
    
        public static void main(String[] args) {
            String s = "We are happy.";
            System.out.println(replaceSpace(s));
        }
    }
    
    
    不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!
  • 相关阅读:
    mongoDB 索引
    mongoDB _id:ObjectId("xxxx")详解
    mongoDB: cursor not found on server
    mongoDB group命令详解
    Python 中,matplotlib绘图无法显示中文的问题
    python常用
    deepin下安装python的Tkinter库
    wireshark抓包常见提示含义解析
    TimeUnit
    Java回调机制解析
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/15002235.html
Copyright © 2011-2022 走看看