js string inversion (reverse order) method
The first type
let str = "i am good man"; let newStr = ('').reverse().join(""); (newStr)
First convert the string into an array, then reverse the array, and finally convert the array into a string
-
split("")
------Split array according to string -
reverse()
-------------------------------------------------------------------------------------------------------------------------------- -
join("")
--------------------------------------------------------------------------------------------------------------------------------
The second type
let str = "i am good man "; let newStr = ""; for(let i = 0;i<;i++){ let s = (-i-1) newStr += s; } (newStr)//nam doog ma i //Start traversing the string from the end,Then splice characters one by one,Get the final result。
Define a new empty string, traversing str, charAt() is a character that extracts a string, first go to the last character, then take the second one, and then take it in turn, put the obtained results in front of the new characters, so as to achieve reverse order
The third type
let str ="i am good man"; let newStr = (str); (().join(""))//nam doog ma i
The execution body of the slice method is changed through the call method. After calling the call method of the array, the string can have the characteristics of the array, so that the reverse method can be called directly, and finally, by calling the join method, the reverse string can be obtained.
js algorithm notes - invert strings
Invert string
Write a function that inverts the input string. The input string is given as a character array char[].
Example 1:
- Enter: ["h","e","l","l","o"]
- Output: ["o", "l", "l", "e", "h"]
Ideas
- Array reverse method
The simplest and most direct solution is that since it is an array output, you can just invert the array reverse method. Since it is an algorithm problem, you definitely don’t want to use the array reverse method to solve it.
- Double pointer method
For strings, we define two pointers (or the index below table), one from the front of the string and one from the back of the string, and the two pointers move to the middle at the same time, and exchange elements.
- Code implementation
/** * @param {character[]} s * @return {void} Do not return anything, modify s in-place instead. */ //Array method implementationvar reverseString = function(s) { return (); }; //Double pointer method implementationvar reverseString = function(s) { let l = -1 let r = while(++l < --r) [s[l], s[r]] = [s[r], s[l]]; return s; };
The above is personal experience. I hope you can give you a reference and I hope you can support me more.