请实现一个函数,把字符串中的每一个空格替换成"%20"。算法
你能够假定输入字符串的长度最大是1000。
注意输出字符串的长度可能大于1000。app
样例
输入:"We are happy."函数
输出:"We%20are%20happy."code
常规思路是从前日后遍历,若是遇到空格,则将空格以后的全部数据移动两个位置,而后设置"%20"。但这样会由于移动数据次数过多而增长时间复杂度。
能够先计算出空格的个数countOfBlank,从而得出新字符串的长度是n + 2*countOfBlank,而后设置字符串的长度为新的长度。接着进行移动字符,从后往前遍历字符串,依次复制字符到最终位置,遇到空格,则填充"%20"。
时间复杂度是O(n),n是字符串长度字符串
class Solution { public String replaceSpaces(StringBuffer str) { if (str == null) return null; int countOfBlank = 0; int oldLength = str.length(); for(int i=0; i<str.length(); i++) { if (str.charAt(i) == ' ') countOfBlank++; } int newLength = str.length() + 2 * countOfBlank; str.setLength(newLength); int oldIndex = oldLength - 1; int newIndex = newLength - 1; //从后往前遍历 while (oldIndex >= 0 && newIndex >= 0) { if (str.charAt(oldIndex) == ' ') { str.setCharAt(newIndex--, '0'); str.setCharAt(newIndex--, '2'); str.setCharAt(newIndex--, '%'); } else { str.setCharAt(newIndex, str.charAt(oldIndex)); newIndex--; } oldIndex--; } return str.toString(); } }