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--;
                }
            }
        }
  • 相关阅读:
    2021.3.16
    2021.3.15
    通过指定的URL获取返回图片的BASE64编码
    Redis系统学习之缓存穿透,缓存击穿,缓存雪崩的概念及其解决方案
    Redis系统学习之其他高可用模型
    Redis系统学习之哨兵模式
    Redis系统学习之主从复制
    Redis系统学习之发布订阅
    Redis系统学习之持久化(AOF)
    Redis系统学习之持久化(RDB)
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821674.html
Copyright © 2011-2022 走看看