zoukankan      html  css  js  c++  java
  • Cracking the Coding Interview Q1.4

    Write a method to replace all spaces in a string with ‘%20’.

    package chapter1;
    
    /**
     * Write a method to replace all spaces in a string with ‘%20’. (Assume string
     * has sufficient free space at the end)
     * 
     * @author jd
     * 
     */
    public class Q1_4 {
    
        /**
         * 1. Count the number of spaces during the first scan of the string. 
         * 2.Parse the string again from the end and for each character: 
         * if a space is encountered, store '%20';
         * else store the character as it is in the newly shifted location.
         */
        public static void replaceSpaces(char[] str, int length) {
            if (str == null)
                return;
            int spaceCount = 0;
            for (int i = 0; i < str.length; i++) {
                if (str[i] == ' ')
                    spaceCount++;
            }
            int newLength = length + 2 * spaceCount;
            for (int i = length - 1, j = newLength - 1; i >= 0 && j >= 0; i--) {
                if (str[i] != ' ') {
                    str[j--] = str[i];
                } else {
                    str[j--] = '0';
                    str[j--] = '2';
                    str[j--] = '%';
                }
    
            }
    
        }
    
        public static void main(String[] args) {
            String str = "abc d e f";
            char[] arr = new char[str.length() + 3 * 2 + 1];
            for (int i = 0; i < str.length(); i++) {
                arr[i] = str.charAt(i);
            }
            replaceSpaces(arr, str.length());
            System.out.println(""" + new String(arr) + """);
        }
    }

    Solution:

    public static void replaceSpaces(char[] str, int length) {
            int spaceCount = 0, index, i = 0;
            for (i = 0; i < length; i++) {
                if (str[i] == ' ') {
                    spaceCount++;
                }
            }
            index = length + spaceCount * 2;
            str[index] = '';
            for (i = length - 1; i >= 0; i--) {
                if (str[i] == ' ') {
                    str[index - 1] = '0';
                    str[index - 2] = '2';
                    str[index - 3] = '%';
                    index = index - 3;
                } else {
                    str[index - 1] = str[i];
                    index--;
                }
            }
        }
  • 相关阅读:
    接口的多实现。
    接口的基本实现。
    构建MVC解决方案(包含哪些项目)
    书目记录
    Chrome浏览器修改user-agent,伪装其他浏览器,附带微信、支付宝user-agent
    [文件]学生信息的简单读入与输出
    scanf高级用法【至此丢弃gets用法 】
    数组,字符串
    [转载]终极解密输入网址按回车到底发生了什么
    typedef 和 #define 的区别
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821674.html
Copyright © 2011-2022 走看看