replace spaces

given an char array and the length of its characters, replace all of the spaces to "%20", we can suppose that this array is long enough to hold new characters. Return the new length of this array.

e.g: "5 6789 "->"5%206789%20";

Solution:

1. Scan the whole array to get the new length.

2. From the end of the new length array, use two pointer to scan the array, when encounter a space, insert "%20" instead.

 

Code:

public int replaceSpaces(char[] str, int length){
    int new_len = length;
    for(int i = 0; i < length; i++){
        if(str[i]==' ')
            new_len+=2;
    }
    int j = new_len;
    for(int i = length-1; i>=0; i--){
        if(str[i]!=' '){
            str[j--]=str[i];
        }else{
            str[j--]='0';
            str[j--]='2';
            str[j--]='%';
        }
    }
    return new_len;
}
View Code

 

posted @ 2017-06-16 11:42  小风约定  阅读(56)  评论(0)    收藏  举报