思路:如果允许额外空间的话,使用辅助空间,线性遍历时间复杂度也是o(n)
如果不允许,则需要对原本的空间进行扩容。计算出空格的个数,对数组需要进行遍历两次所以时间复杂度o(2n)
static String replaceString(String s) {
StringBuilder sb = new StringBuilder(s);
int spaceCount = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ' ')
spaceCount++;
}
int oldLen = sb.length();
int newLen = oldLen + spaceCount * 2;
sb.setLength(newLen);
int newIndex = newLen - 1;
int oldIndex = oldLen - 1;
for (; oldIndex > 0; oldIndex--) {
if (sb.charAt(oldIndex) == ' ') {
sb.setCharAt(newIndex--, '0');
sb.setCharAt(newIndex--, '2');
sb.setCharAt(newIndex--, '%');
} else {
sb.setCharAt(newIndex--, sb.charAt(oldIndex));
}
}
return sb.toString();
}