Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91382791
welcome to my blog
5 face questions: replace spaces
Title Description
Please implement a function, a string to replace each space to "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.
Thinking
- First clear demand if it is to be replaced on the original string, it is possible to modify memory in the back cover of the string; If it is to create a new string and replace it on the new string, then you can assign yourself enough much memory
- Requirements: Returns a new string
- Create a new StringBuffer, one by one copy, special treatment when experiencing space with if else on it
- Opening a mistake, StringBuffer (newLen) does not create a newLen length of string, but to create a long string of 0's
the complexity
Time complexity: O (n)
space complexity: O (n)
Reflection
Copy selected from front to back or copied from the back, depending on the circumstances to be determined. This problem may determine the length of the new string, so the front to back or from the back row are
public class Solution {
public String replaceSpace(StringBuffer str) {
// 健壮性判断
if(str == null )
return null;
// 正常判断
/*
1. 统计空格个数
2. 明确新字符串长度
3. 开始复制
*/
// 1
int originalLen = str.length();
int numOfBlank = 0;
for(int i=0; i<originalLen; i++){
if(str.charAt(i) == ' ')
numOfBlank++;
}
// 2
int newLen = originalLen + 2*numOfBlank;
StringBuffer sb = new StringBuffer();
// 3
for(int i=0; i<originalLen; i++){
if(str.charAt(i) == ' '){
sb.append('%'); // 在末尾追加
sb.append('2');
sb.append('0');
}
else
sb.append(str.charAt(i));
}
return sb.toString();
}
}