zoukankan      html  css  js  c++  java
  • 【剑指offer】字符串替换

    请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

    *StringBuffer 扩容 str.setLength(扩容大小)

    *思路:将原字符数组扩容至目标大小后,从后往前移动字符串,可大大减小移动次数

    public class Solution {
        
         public String replaceSpace(StringBuffer str) {
                 int originalLength = str.length();
                 int capacityRequired = (calculateLength(str) << 1) + str.length();
                 //在原大小上扩容2*空格数
                 str.setLength(capacityRequired);
                 for(int i=originalLength-1, j=capacityRequired-1; i >= 0; i--, j--){
                     if(str.charAt(i)==' '){
                         str.setCharAt(j-2, '%');
                         str.setCharAt(j-1,'2');
                         str.setCharAt(j, '0');
                         j=j-2;
                     }else{
                         str.setCharAt(j, str.charAt(i));
                     }
                 }
                 
                return str.toString().substring(0,capacityRequired);
            }
         private int calculateLength(StringBuffer str){
             int countSpace = 0;
             for(int i=0; i < str.length(); i++){
                 if(str.charAt(i)==' '){
                     countSpace++;
                 }
             }

  • 相关阅读:
    TT ERP 业务功能分析 汇总
    CSRedis 使用说明
    多线程,控制Task的20个并发数量,全部子线程执行完后,获取所有返回的值
    React 和 vue的区别以及React的环境搭建,运行
    jar 包上传后 Xshell启动
    FileZilla 上传文件
    vue多环境配置
    el-tree 节点常用操作
    钉钉微应用
    Bonobo Git Server
  • 原文地址:https://www.cnblogs.com/singular/p/10014923.html
Copyright © 2011-2022 走看看