• 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--;
                }
            }
        }
  • 相关阅读:
    实验一 GIT 代码版本管理
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业01-线性表
    C博客作业05--2019-指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    python exp4 jieba+wordcloud
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821674.html
Copyright © 2020-2023  润新知