JS replace spaces

Please implement a function to replace each space in the string s with "%20".

  • Example:

Input: s = "We are happy."
Output: "We%20are%20happy."
Constraints: 0 <= length of s <= 10000

  • problem solving ideas

There are many solutions to this problem, which can be easily solved by using many native api APIs, for example:

  • repleace/replaceAll
  • encodeURIComponent
  • Split/join
    or direct brute force solution, etc...
    But we know that these are definitely not the purpose of the investigation, what we need to do is how to reduce the complexity as much as possible in the process of manual implementation!
    Because the string in JS cannot be modified, once the string variable is reassigned, it will take time and space to create a new string, which increases the complexity!
    So here we use an array to operate, the process is as follows:
    1. Convert the string to an array, and then count the number of spaces in it.
    2. According to the number of spaces and the effective character length of the original string, calculate an array that just stores the length of the replaced character.
    3. Create two pointers, one refers to the end of the array, and the other refers to the end of the valid bit of the string to realize in-place modification.
    It is worth noting that: when traversing the array, it must be traversed from the back to the front, so as to avoid the characters being modified from the front to the back, resulting in errors!

method one

/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function(s) {
    
    
    return s.replaceAll(" ","%20");
};
replaceSpace("We are happy.");

Method Two

/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function(s) {
    
    
    //return encodeURI(s);
    return encodeURIComponent(s);
};
replaceSpace("We are happy.");

Method Three

/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function(s) {
    
    
    var arr = s.split(" ");
    return arr.join("%20");
};
replaceSpace("We are happy.");

Method four

/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function(s) {
    
    
    s = s.split("");
    let oldLen = s.length;
    let spaceCount = 0;
    for (let i = 0; i < oldLen; i++) {
    
    
        if (s[i] === ' ') spaceCount++;
    }
    s.length += spaceCount * 2;
    for (let i = oldLen - 1, j = s.length - 1; i >= 0; i--, j--) {
    
    
        console.log(s[i],s[j]);
        if (s[i] !== ' ') s[j] = s[i];
        else {
    
    
            s[j - 2] = '%';
            s[j - 1] = '2';
            s[j] = '0';
            j -= 2;
        }
    }
    return s.join('');
};
replaceSpace("We are happy.");

Welcome to the same text short book number: JS replace spaces

Guess you like

Origin blog.csdn.net/qq_38970408/article/details/122176385