Lintcode: Space substitution

Source: Internet
Author: User
Tags lintcode

Lintcode: Space substitution

Precautions

If you are using Java or Python, use a character array in your program to represent the string.

Python

Method One: This method does not use a character array, directly using the string array, although can pass, but do not meet the requirements, see Method 2.

 class solution:    # @param {char[]} string:an array of char    # @param {int} length:the True length of the string    # @return {int} The true length of new string     def Replaceblank(self, string, length):        # Write Your code here        ifString = =None:return 0         while "' inchString:m = String.index ("') String[m] ='%20 'Length + =2        returnLength

Method Two:

classSolution: #@param{Char[]}string: An array of Char #@param{int} length:thetrueLength of thestring#@return{int} ThetrueLength ofNew stringdef replaceblank (self,string, length): # Write Your code hereif string= = None:return 0         while "' inch string: M =string. Index ("') n = Length length = length +2             whilen > M:string[n+2] =string[n] N-=1            string[M] ='% '            string[m+1] =' 2 '            string[m+2] =' 0 '        returnLength
Java
 Public classSolution {/** * @param string:an array of Char * @param length:the True Length of the string * @return: The True Length of new String * /     Public int Replaceblank(Char[]string,intLength) {//Write your code here        if(Length = =0){return 0; } while(Contains (string)){intM = Index (string);intn = length; Length = length +2; while(n > M) {string[n +2] =string[n]; N-=1; }string[M] ='% ';string[m+1] =' 2 ';string[m+2] =' 0 '; }returnLength }Private StaticBooleancontains(Char[]string){ for(intI=0; i<string. length; i++) {if(string[I] = ="'){return true; }        }return false; }Private Static int Index(Char[]string){ for(intI=0; i<string. length; i++) {if(string[I] = ="'){returnI }        }return 0; }}

Lintcode: Space substitution

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.