212. Space replacement "Lintcode by Java"

Source: Internet
Author: User
Tags lintcode

Description

Write a method to replace all spaces in a string with %20 . The string is given in a characters array, you can assume it have enough space for replacement and you are given the true L Ength of the string.

You code should also return the new length of the string after replacement.

If you is using Java or python,please use characters array instead of string.

Example

Given "Mr John Smith" , length = 13 .

The string after replacement should "Mr%20John%20Smith" is, you need to change the string in-place and return the new length 17 .

Challenge

Do it in-place.

Problem solving: Give a character array, where the space is changed to % 20. because it is in-situ conversion, can not apply for additional space, then can only step back to move backwards. Because the space is converted to "%20", the space used to occupy a unit, now need to occupy three units, as long as the original space behind all the numbers are moved backward two squares. In the process of moving, length also varies. The code is as follows:

1  Public classSolution {2     /*3 * @param string:an array of Char4 * @param length:the True length of the string5 * @return: The true length of the new string6      */7      Public intReplaceblank (Char[] String,intlength) {8         //Write your code here9          for(inti = 0; I <length;) {Ten             //If a space is found One             if(String[i] = = "){ A                  for(intj = length-1; J >= I+1; j--){ -STRING[J+2] =String[j]; -                 } thestring[i++] = '% '; -string[i++] = ' 2 '; -string[i++] = ' 0 '; -Length = length+2; +}Else{ -i++; +             } A         } at         returnlength; -     } -}

212. Space replacement "Lintcode by Java"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.