Sword refers to offer, face question 4, replace space, Java writing __java

Source: Internet
Author: User

Title: Please implement a function that replaces a space in a string with "%20". For example, when the string is Are Happy, the replaced string is We%20are%20happy.

The idea is if you insert from left to right, the time complexity is O (N2), first determine the number of spaces, and then determine the replacement string length, from right to left to insert the time complexity of O (n)

Simple, but highly time-complicated code:

public class Solution {public
    String replacespace (StringBuffer str) {return
        str.tostring (). ReplaceAll ("\\s", "%20");
    }
My Code:

public class Solution {public String replacespace (StringBuffer str) {int originallength = s  Tr.length ()-1;   String str original length int numberofblank = 0;
        Number of spaces//int i = 0;
            for (char c:str.tostring (). ToCharArray ()) {if (c = = ") {numberofblank++;
           an int newlength = originallength + numberofblank*2+1;
           Str.setlength (newlength);
           Newlength = newLength-1; while (originallength >= 0 && newlength > Originallength) {if (str.charat) = =
                      ') {Str.setcharat (newlength--, ' 0 ');
                      Str.setcharat (newlength--, ' 2 ');
                  Str.setcharat (newlength--, '% ');
                  }else{Str.setcharat (newlength--, Str.charat (originallength));
           } originallength--;
    return str.tostring (); }
public static void Main (String args[]) {
StringBuffer str = new StringBuffer ();
Str.append ("HelloWorld");
}


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.