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

  • 相关阅读:
    解析三种常见分布式锁的实现
    RabbitMQ基础概念详解
    数据库事务概念
    ECIF与CRM
    MQ(消息队列)学习
    数据粒度的设计
    链表之 头节点与尾指针 区别
    牛客之错题(2016.1.15) && 带头节点与不带头的区别
    数据结构之递归回溯算法
    LeetCode--Single Number
  • 原文地址:https://www.cnblogs.com/singular/p/10014923.html
Copyright © 2011-2022 走看看