替换空格-剑指Offer

替换空格

题目描述

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

思路

  1. 遍历一遍,统计空格数量,扩大相应容量
  2. 两个指针,一个指向旧的长度,一个新的长度,从后往前走,一个一个走,遇到空格,right走3个,left走1个
  3. left == right或left == 0就不用接着走了

代码

public class Solution02 {
public String replaceSpace(StringBuffer str) {
    int oldLength = str.length();
    int numOfSpace = 0;
    for (int i = 0; i < oldLength; i++) {
        if (str.charAt(i) == ' ') {
            numOfSpace++;
        }
    }

    int newLength = oldLength + numOfSpace * 2;
    int left = oldLength - 1;
    int right = newLength - 1;
    for (int n = 0; n < numOfSpace * 2; n++){
        str.append(' ');
    }
    while (left >= 0 && right > left) {
        if (str.charAt(left) == ' ') {

            str.setCharAt(right--, '0');
            str.setCharAt(right--, '2');
            str.setCharAt(right--, '%');
            left--;
        } else {
            str.setCharAt(right--, str.charAt(left--));
        }
    }
    return str.toString();
}
public static void main(String[] args) {
    StringBuffer test = new StringBuffer("hello world ");
    Solution02 solution = new Solution02();
    System.out.println(solution.replaceSpace(test));

}

}

 

新人水平有限,请大家多多指教!

原文地址:https://www.cnblogs.com/rosending/p/5603668.html