
Data Structures and Algorithms - String reversal
As someone who does not come from a Computer science background, data structures and algorithms always felt daunting. After taking a few online courses things started to click. In this series of posts I'm going to discuss some common data structures and algorithms and how to solve them. Resources will be linked at the bottom of every post.
So lets start with String Reversal.
String reversal is a common interview question. The interviewer may ask you to preform this action in multiple ways.
Before we start we need to know the expected results of reversing a string:
Ex. Input: "Hello, world!" Output: "!dlrow ,olleH"
Now, I am going to show you three ways to do this.
1. Using built in methods
function reverseString(str){
return str.split('').reverse().join('');
}- split: The split method turns a string into an array of strings based on the separator indicated in the split function.
- ex. "Hello, world!".split(' ') --> ["Hello," , "world!"]
- ex. "Hello, world!".split(', ') --> ["Hello" , "world!"]
- reverse: The reverse method reverses an array. The first element becomes the last and the last becomes the first
- join: The join method returns a new string by concatenating all of the elements in an array and separating them by commas or the separator indicated in the function
- ex. ["Hello," , "world!"].join() --> "Hello,,world!"
- ex. ["Hello," , "world!"].join(' ') --> "Hello, world!"
- ex. ["Hello," , "world!"].join('-') --> "Hello,-world!"
2. Decrementing for loop
function reverseString(str) {
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}- Outside of the built in functions a for loop can be seen as a brute force approce to string reversal
3. for...of loop
function reverse(str) {
var reversed = '';
for (let char of str) {
reversed = char + reversed;
}
return reversed;
}- The for of loop is a new feature from ES6. I prefer this method to the decrementing for loop because the code is cleaner and less susceptible to typos.
References