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

  • 相关阅读:
    Ubuntu下errno值
    Git 经常使用命令总结
    【我们都爱Paul Hegarty】斯坦福IOS8公开课个人笔记38 Unwind Segue反向过渡
    高斯噪声
    小记5.8面试
    基数排序之多keyword排序运用队列
    广告贴
    输入字符串反序输出
    Codeforces Round #313 A. Currency System in Geraldion
    matlab中怎样加入凝视
  • 原文地址:https://www.cnblogs.com/singular/p/10014923.html
Copyright © 2011-2022 走看看