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++;
                 }
             }

  • 相关阅读:
    LCS LIS
    补个线段树
    洛谷1522
    AC自动机
    WF 2017 I
    WF2017 E
    最小生成树计数 基尔霍夫矩阵树定理
    bitonic tour luogu1523
    code+11月月赛
    模拟退火
  • 原文地址:https://www.cnblogs.com/singular/p/10014923.html
Copyright © 2011-2022 走看看