-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathReverseString.js
72 lines (54 loc) · 1.56 KB
/
ReverseString.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Given a string A. Return the string A after reversing the string word by word.
Below is the implementation of program in 3 different ways -
1. Iterative
2. Built-In functions
3. Recursive
*/
// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });
// Iterative method
function ReverseStringIterative(str) {
let arrayString = str.split("");
let reversedArray = [];
function addToArray(array) {
if (array.length > 0) {
reversedArray.push(array.pop()); // pop the element from array & push it in the reversedArray array
addToArray(array);
}
return;
}
// Pass array of strings
addToArray(arrayString);
console.log("Reverse String Iterative - ", reversedArray.join(""));
return reversedArray.join("");
}
// Using in-built methods of JavaScript
function ReverseString(str) {
str = str === "" ? "" : str.split("").reverse().join("");
console.log("Reverse String - ", str);
return str;
}
// Recursive approach
function ReverseStringRecursive(str) {
if (str === "") {
return "";
} else {
return ReverseStringRecursive(str.substr(1)) + str.charAt(0);
}
}
// Get the user input
let string = prompt("Enter String to reverse - ");
// Call the algorithm
ReverseStringIterative(string);
ReverseString(string);
// Call the recursive algorithm
let result = ReverseStringRecursive(string);
console.log("Reverse String Recursive - ", result);
/*
> node ReverseString
Enter String to reverse - node
Reverse String Iterative - edon
Reverse String - edon
Reverse String Recursive - edon
*/