"The offer to prove safety" interview questions replace spaces 4

"Prove safety offer" answers, analysis and notes for Java

"The offer to prove safety" interview questions 4: replace the space
for a sufficiently long array of characters, wherein some characters, a '' (blank) replaced with '%' '2' '0' three characters from the original character segments' \ 0 'end

Method book: If this question and replaced from start to finish scanning the array, the array will be directed to the mobile. If you do not move elements from start to finish processing seems to be no idea. To see the title of a sufficiently long array, we have to think from the back way process. We calculate the length of the array after replacement, can simply deduce the original character when the segment processing to the first character, a new character segments to be processed first character.

    public void replace(char[] c){
        if(c == null || c.length == 0)return;

        int originTail = -1;
        int newTail = -1;

        int i = 0;
        while(c[i] != '\0'){
            originTail++;
            if(c[i] == ' '){
                newTail += 3;
            }else{
                newTail ++;
            }
            i++;
        }
        c[newTail+1] = '\0';
        while(originTail >= 0){
            if(c[originTail] != ' '){
                c[newTail] = c[originTail];
                newTail--;
            }else{
                c[newTail--] = '0';
                c[newTail--] = '2';
                c[newTail--] = '%';
            }
            originTail--;
        }
    }

Guess you like

Origin www.cnblogs.com/czjk/p/11589621.html