zoukankan      html  css  js  c++  java
  • 剑指Offer:替换空格(5)

    题目描述:

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

    解题思路:

    在字符串后任意填充字符,使得字符串替换前的长度=替换后的长度,例如上面这个例子,替换前长度为12,替换后的长度为16,所以在原来字符串的基础上填充2位.

    p1指向填充前的末尾,p2指向填充后的末尾:

    然后p1,p2一起前移,如果p1不是空格,则p2=p1;如果p1是空格,则p2依次输入"02%"

     1 public class Solution {
     2     public String replaceSpace(StringBuffer str) {
     3         int p1 = str.length()-1;
     4         for(int i=0;i<=p1;i++){
     5             if(str.charAt(i)==' ')
     6                 str.append("  ");
     7         }
     8         int p2 = str.length()-1;
     9         while(p1>=0 && p2>p1){
    10             char c = str.charAt(p1--);
    11             if(c==' '){
    12                 str.setCharAt(p2--,'0');
    13                 str.setCharAt(p2--,'2');
    14                 str.setCharAt(p2--,'%');
    15             }else{
    16                 str.setCharAt(p2--,c);
    17             }
    18         }
    19         return str.toString();
    20     }
    21 }
  • 相关阅读:
    Node.js NPM 包(Package)
    Node.js NPM 作用
    Node.js NPM 介绍
    Node.js NPM 教程
    Node.js NPM 教程
    Node.js 发送Email
    Node.js 上传文件
    Node.js 事件
    Node.js NPM
    Node.js 文件系统模块
  • 原文地址:https://www.cnblogs.com/lkylin/p/13468649.html
Copyright © 2011-2022 走看看