Replace spaces - offer to prove safety

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.

 

java function can be directly solved it makes no sense to write c ++.

Ideas: This title if allowed to open up new space is relatively simple, but if you are not allowed to open up a new space, but also enough to ensure that the original length of the string, then the how to solve is the key.

Providing two i, j mark, calculate the length after the replacement, i denotes the original string of the last subscript, j indicates the index calculated last string, and then go from the back would be finished.

class Solution {
 public :
     void replaceSpace ( char * STR, int length) {
         IF (STR == nullptr a length || <= 0 ) {
             return ; 
                                   } 
        int space_count = 0 ;
 // the number of calculation spaces, to facilitate replacement character is calculated string length 
        for ( int I = 0; I <length; I ++ ) {
             IF (STR [I] == '' ) { 
                space_count ++ ; 
            } 
        } 
        int nlength space_count + = 2 * length;
        int i = length-1;
        int j = nlength-1;;
        while(i >= 0){
            if(str[i] == ' '){
                str[j--]='0';
                str[j--]='2';
                str[j--]='%';
                i --;
            }else{
                str[j--] = str[i--];
            }
        }
    }
};

 

Guess you like

Origin www.cnblogs.com/nlw-blog/p/12409009.html