Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.

preface

Data structure and algorithm belong to the internal work of the developer, no matter how the front-end technology changes, how the framework updates, how the version iteration, it is the same content. Always remember in the byte youth training camp, moon shadow teacher said a word, do not ask front-end learning algorithm. Everyone in computer science needs to know about algorithms and has the subconscious to write high-quality code.

(1) Replace Spaces

1.1 Description

Implement a function that replaces each space in the string s with “%20”.

Example 1:

Input: s = "We are happy." Output: "We%20are%20happy.Copy the code

Limitations:

  • 0 <= the length of s <= 10000

1.2 Topic Analysis

Method 1: directly use the string split method, convert the string into an array, and then use the join method to merge the middle insert %20

var replaceSpace = function(s) {
    return s.split(' ').join('% 20')};Copy the code

Method two iterates through the string and inserts %20 if it encounters a null value

var replaceSpace = function(s) {
    let res = ""
    for(const i in s){
        const cur = s[i]
        if(cur==' '){
            res+='% 20'
        }else{
            res+=cur
        }
    }
    return res
};
Copy the code

(二) Print the linked list from end to end

2.1 Problem Description

Enter the head node of a linked list and return the value of each node from end to end (as an array).

Example 1:

Input: head = [1,3,2] output: [2,3,1]Copy the code

Limitations:

  • 0 <= List length <= 10000

2.2 Problem Analysis

We just iterate over the node until we get to the end of the list, each time the value of the node is inserted at the top of the array by unshift.

var reversePrint = function(head) {
    const res = []
    let p = head
    while(p){
        res.unshift(p.val)
        p = p.next
    }
    return res
};
Copy the code

conclusion

  • The split method of strings converts a string to an array
  • Array.prototype.join converts arrays to strings

I’m Shao Xiaobai, a junior student in the front end field. Welcome to 👍 for comments. Borrow fish guy’s word: no matter dish not dish, but love!