【剑指offer】替换空格
替换空格
http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
- 直接调用函数和new StringBuffer然后append 简直没谁了...
public class Solution { public static String replaceSpace(StringBuffer str) { if (str == null) { return null; } int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { count++; } } int l = str.length() - 1; int r = l + count * 2; str.setLength(r + 1); while (l >= 0) { if (str.charAt(l) != ' ') { str.setCharAt(r, str.charAt(l)); r--; } else { str.replace(r - 2, r + 1, "%20"); r -= 3; } l--; } return str.toString(); } }