新手练手感--leetCode字符串替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
//如果直接遍历碰到空格,后面所有的往后移动,则徒劳的移动太多, //目标:所有的字符串一次移动到位,移动最少 //1.统计空格的数量 //2.确定直接就在原来的字符串上移动,节省空间 //3.确定从前往后遍历(需要新开字符串),还是从后往前遍历(不用新开,从后往前没一个字符串都是一次移动到位) public class Solution { public String replaceSpace(StringBuffer str) { //是空的话返回空 if(str == null || str.length() == 0) { return ""; } //统计空格数量 int spaceNum = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == ' ') { spaceNum++; } } if(spaceNum == 0) { return str.toString(); } //计算扩展前后的长度 int oldLength = str.length(); int newLength = oldLength + spaceNum * 2; str.setLength(newLength); //从后到前遍历,往后移动(spaceNum - i)个位置,如果是空格在进行替换 for(int i = oldLength - 1; i >= 0; i--) { if(str.charAt(i) != ' ') { str.setCharAt(i + spaceNum * 2, str.charAt(i)); } else { str.setCharAt(i + spaceNum * 2, '0'); str.setCharAt(i + spaceNum * 2 - 1, '2'); str.setCharAt(i + spaceNum * 2 - 2, '%'); spaceNum--; } } return str.toString(); } }