• 替换空格 4


    先遍历每个字符统计空格数 String.charAt()

       

    根据空格数计算新的长度 newLength=oriLength+2*NumOfBlank

       

    新建一个newLength长度的字符数组tempChars用于存放替换空格之后的字符数组

       

    利用System.arraycopy函数将原字符串转换为数组拷贝到新的字符数组tempChars

       

    从新字符数组末尾开始遍历,用一个index1指向新字符数组末尾,用一个index2指向原字符数组末尾所在新字符数组的位置,将原字符数组逐个复制到新的字符数组的位置,遇到空格,替换,此时index1动,index2不动

       

    复杂度O(n),如果是从前往后复制的话复杂度O(n^2)

       

    package replaceBlank;

       

    public class ReplaceBlank {

    public static int getBlankNum(String testString) {

    int count = 0;

    for (int i = 0; i < testString.length(); i++) {

    String tempString = String.valueOf(testString.charAt(i));

    if (tempString.equals(" ")) {

    count++;

    }

    }

       

    return count;

    }

       

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    String string = "we are here";

    replaceBlank(string);

    }

       

    static void replaceBlank(String string){

    if (string==null) {

    return;

    }

    int orgLength=string.length();

    int numOfBlank=0;

    for (int i = 0; i < string.length(); i++) {

    String tempString = String.valueOf(string.charAt(i));

    if (tempString.equals(" ")) {

    numOfBlank++;

    }

    }

    int newLength=orgLength+2*numOfBlank;

    char[] tempChars=new char[newLength];

    System.arraycopy(string.toCharArray(), 0, tempChars, 0, string.length());

    System.out.println("orgLength:"+orgLength+" "+"numOfBlank:"+numOfBlank);

    int indexOfOrgChars=orgLength-1;

    int indexOfNewChars=newLength-1;

    while (indexOfOrgChars>=0&&indexOfNewChars!=indexOfOrgChars) {

    if (tempChars[indexOfOrgChars]==' ') {

    tempChars[indexOfNewChars--]='%';

    tempChars[indexOfNewChars--]='2';

    tempChars[indexOfNewChars--]='0';

    }else {

    tempChars[indexOfNewChars--]=tempChars[indexOfOrgChars];

    }

    indexOfOrgChars--;

    }

    System.out.println(tempChars);

    }

    }

  • 相关阅读:
    es6学习笔记
    vue.js项目目录结构说明
    js 数组操作总结
    js 数组去重方法
    HTTP协议三次握手过程
    MVC与MVVM模式对比
    谱面编辑器
    LL谱面分析和难度标定
    SLP的模块结构
    LL基本姿势
  • 原文地址:https://www.cnblogs.com/keedor/p/4379086.html
Copyright © 2020-2023  润新知