1. 程式人生 > >《劍指offer》系列 替換空格(Java)

《劍指offer》系列 替換空格(Java)

連結

牛客:替換空格

題目描述

請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

思路

先遍歷一遍,知道空格數量,然後從後面替換,因為前面替換會反覆的移動字串。

程式碼

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ') {
                count++;
            }
        }
        char[] newStr = new char[str.length() + count * 2];
        int index = newStr.length - 1;
        for (int i = str.length() - 1; i >= 0 && index >= 0; i--) {
            if (str.charAt(i) == ' ') {
                newStr[index--] = '0';
                newStr[index--] = '2';
                newStr[index--] = '%';
            } else {
                newStr[index--] = str.charAt(i);
            }
        }
        return new String(newStr);
    }
}