Tri spôsoby, ako obrátiť reťazec v JavaScripte

Tento článok je založený na základnom skriptovaní algoritmu Free Code Camp „Obrátiť reťazec“

Reverzia reťazca je jednou z najčastejšie kladených otázok o JavaScripte v technickom kole pohovoru. Anketári vás môžu požiadať, aby ste napísali rôzne spôsoby obrátenia reťazca, alebo vás môžu požiadať o obrátenie reťazca bez použitia vstavaných metód, alebo vás dokonca môžu požiadať o obrátenie reťazca pomocou rekurzie.

Existujú potenciálne desiatky rôznych spôsobov, ako to urobiť, s výnimkou zabudovanej reverznej funkcie, pretože JavaScript taký nemá.

Ďalej uvádzam moje tri najzaujímavejšie spôsoby riešenia problému obrátenia reťazca v JavaScripte.

Algoritmická výzva

Poskytnutý reťazec otočte späť.

Možno budete musieť reťazec premeniť na pole, kým ho budete môcť obrátiť.

Výsledkom musí byť reťazec.

function reverseString(str) { return str; } reverseString("hello");

Poskytnuté testovacie prípady

  • reverseString („ahoj“) by sa mal zmeniť na „olleh
  • reverseString („Howdy“) by sa malo zmeniť na „ydwoH“
  • reverseString („Pozdrav zo Zeme“) by mal vrátiť „htraE morf sgniteerG“

1. Obráťte reťazec pomocou vstavaných funkcií

Pre toto riešenie použijeme tri metódy: metódu String.prototype.split (), metódu Array.prototype.reverse () a metódu Array.prototype.join ().

  • Metóda split () rozdelí objekt String na pole reťazcov oddelením reťazca do podreťazcov.
  • Metóda reverse () obráti pole na danom mieste. Prvý prvok poľa sa stáva posledným a posledný sa stáva prvým.
  • Metóda join () spája všetky prvky poľa do reťazca.
function reverseString(str) { // Step 1. Use the split() method to return a new array var splitString = str.split(""); // var splitString = "hello".split(""); // ["h", "e", "l", "l", "o"] // Step 2. Use the reverse() method to reverse the new created array var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse(); // ["o", "l", "l", "e", "h"] // Step 3. Use the join() method to join all elements of the array into a string var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join(""); // "olleh" //Step 4. Return the reversed string return joinArray; // "olleh" } reverseString("hello");

Spojenie troch metód dohromady:

function reverseString(str) { return str.split("").reverse().join(""); } reverseString("hello");

2. Obráťte reťazec so znížením hodnoty pre slučku

function reverseString(str) { // Step 1. Create an empty string that will host the new created string var newString = ""; // Step 2. Create the FOR loop /* The starting point of the loop will be (str.length - 1) which corresponds to the last character of the string, "o" As long as i is greater than or equals 0, the loop will go on We decrement i after each iteration */ for (var i = str.length - 1; i >= 0; i--) { newString += str[i]; // or newString = newString + str[i]; } /* Here hello's length equals 5 For each iteration: i = str.length - 1 and newString = newString + str[i] First iteration: i = 5 - 1 = 4, newString = "" + "o" = "o" Second iteration: i = 4 - 1 = 3, newString = "o" + "l" = "ol" Third iteration: i = 3 - 1 = 2, newString = "ol" + "l" = "oll" Fourth iteration: i = 2 - 1 = 1, newString = "oll" + "e" = "olle" Fifth iteration: i = 1 - 1 = 0, newString = "olle" + "h" = "olleh" End of the FOR Loop*/ // Step 3. Return the reversed string return newString; // "olleh" } reverseString('hello');

Bez komentov:

function reverseString(str) { var newString = ""; for (var i = str.length - 1; i >= 0; i--) { newString += str[i]; } return newString; } reverseString('hello');

3. Obráťte reťazec pomocou rekurzie

Pre toto riešenie použijeme dve metódy: metódu String.prototype.substr () a metódu String.prototype.charAt ().

  • Metóda substr () vracia znaky v reťazci začínajúcom na zadanom mieste prostredníctvom zadaného počtu znakov.
"hello".substr(1); // "ello"
  • Metóda charAt () vracia zadaný znak z reťazca.
"hello".charAt(0); // "h"

Hĺbka rekurzie sa rovná dĺžke reťazca. Toto riešenie nie je najlepšie a bude naozaj pomalé, ak bude reťazec veľmi dlhý a veľkosť zásobníka bude hlavným problémom.

function reverseString(str) { if (str === "") // This is the terminal case that will end the recursion return ""; else return reverseString(str.substr(1)) + str.charAt(0); /* First Part of the recursion method You need to remember that you won’t have just one call, you’ll have several nested calls Each call: str === "?" reverseString(str.subst(1)) + str.charAt(0) 1st call – reverseString("Hello") will return reverseString("ello") + "h" 2nd call – reverseString("ello") will return reverseString("llo") + "e" 3rd call – reverseString("llo") will return reverseString("lo") + "l" 4th call – reverseString("lo") will return reverseString("o") + "l" 5th call – reverseString("o") will return reverseString("") + "o" Second part of the recursion method The method hits the if condition and the most highly nested call returns immediately 5th call will return reverseString("") + "o" = "o" 4th call will return reverseString("o") + "l" = "o" + "l" 3rd call will return reverseString("lo") + "l" = "o" + "l" + "l" 2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e" 1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h" */ } reverseString("hello");

Bez komentov:

function reverseString(str) { if (str === "") return ""; else return reverseString(str.substr(1)) + str.charAt(0); } reverseString("hello");

Podmienený (ternárny) operátor:

function reverseString(str) { return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0); } reverseString("hello");

Reversing a String in JavaScript is a small and simple algorithm that can be asked on a technical phone screening or a technical interview. You could take the short route in solving this problem, or take the approach by solving it with recursion or even more complex solutions.

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

Three ways to repeat a string in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

Two ways to confirm the ending of a String in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.

Three Ways to Factorialize a Number in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

Two Ways to Check for Palindromes in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

Three Ways to Find the Longest Word in a String in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

Three Ways to Title Case a Sentence in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

# StayCurious, # KeepOnHacking & # MakeItHappen!

Zdroje

  • metóda split () - MDN
  • metóda obráteného () - MDN
  • metóda join () - MDN
  • Dĺžka reťazca - MDN
  • metóda substr () - MDN
  • charAt () metóda - MDN