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; }

浙公网安备 33010602011771号