方法一:
public class Solution {
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
public int replaceBlank(char[] string, int length) {
int newLength = length;
for(int i = 0; i < length; i++){
if(string[i] == ' '){
newLength += 2;
}
}
int index = newLength;//一定要保留新字符串长度,以便return newLength;
for(int i = length - 1; i >= 0; i--) {
if( string[i] == ' '){
string[--index] = '0';
string[--index] = '2';
string[--index] = '%';
}else {
string[--index] = string[i];
}
}
return newLength;
}
}
方法二:
public class Solution {
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
static int i;
public int replaceBlank(char[] string, int length) {
// Write your code here
int blankNumber = 0;
for( i = length-1; i >= 0 ; i-- ) {//遍历数组
if(string[i] == ' ') {//遇到空格
blankNumber++;
for (int j = length-1; j > i; j--){
//将空格后的每个字符串后移2位(为了给2和0腾出空间),从最后一个字符开始移动!
string[j+2] = string[j];
}
string[i] = '%';
string[i+1] = '2';
string[i+2] = '0';
}
}
int newLength = length + 2*blankNumber;
return newLength;
}
}
新字符串的长度一定要通过 原字符串长度+2*空格数 获得,不然在lintcode上提交会出错。