Replace all spaces in a char array with the three characters '%20'.


  • 1
    D
    public class Solution{
    
    public void escape(char[] str, int length){
    
    int numSpaces = 0;
    for (int i=0; i<length; i++){
    	if (str[i] == ' ') numSpaces++;
    }
    int lastIndex = (length + numSpaces*2)-1;
    
    int finalLength = lastIndex + 1;
    
    for (int j = lastIndex;j>0;j--){
    	if (str[length-1] != ' '){
    		str[j] = str[length-1];
    	}
    	if (str[length-1] == ' ' ){
    		str[j] = '0';
    		str[--j] = '2';
    		str[--j] = '%';
    	}
    	--length;
    }
    for (int k =0; k<finalLength; k++){
    	System.out.println(str[k]);
    }
    }
    public static void main(String[] args){
    	Solution s = new Solution();
    	char[] str = {'f','o','o',' ','b','a','r','1','1'};	
    	s.escape(str,7);
    }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.