Introduction
The Data Structures and Algorithms Practice series starts with a very simple yet famous question, i.e. - Reverse a String.
I would primarily be using JavaScript as a programming language for this series. Implementations via C#, Java will be thought of as of later.
Problem Statement
Reverse a input string
Ex:
Hello World
-> dlroW olleH
Implementations
1) Using For Loop:
We run the for loop in backwards direction - starting from the last character of the string.
//using for loop
function reverseString(str) {
let result = "";
for (let i = str.length - 1; i >= 0; i--) {
result = result + str[i];
}
return result;
}
console.log(reverseString("Brown Fox"));
console.log(reverseString("Hello World 1 !!!"));
2) Using for of loop:
//using for-of loop
function reverseUsingForOfLoop(str) {
let result = "";
for (let item of str) {
result = item + result;
}
return result;
}
console.log(reverseUsingForOfLoop("Black Fox"));
console.log(reverseUsingForOfLoop("Hello World 2 !!!"));
3) Using reverse() method on string array:
We would convert the input string into an array -> apply reverse() method on the array -> join the array back to the reversed string.
function reverseStringUsingReverse(str) {
return str.split("").reverse().join("");
}
console.log(reverseStringUsingReverse("Blue Fox"));
console.log(reverseStringUsingReverse("Hello World 3 !!!"));
4) Using reduce() method
We would convert the string to an array and feed the array to the reduce method in order to reverse it.
//using reduce method to reverse a string
function reverseUsingReduce(str) {
return str.split("").reduce((rev, item) => item + rev, "");
}
console.log(reverseUsingReduce("Red Fox"));
console.log(reverseUsingReduce("Hello World 4 !!!"));