Skip to content

Commit 39b6426

Browse files
committed
palindrome
1 parent 9fbcabe commit 39b6426

1 file changed

Lines changed: 99 additions & 0 deletions

File tree

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// 16. Check if String is Palindrome
2+
3+
// Method 1: Naive Approach
4+
5+
{
6+
function check_palindrome(str) {
7+
let j = str.length - 1;
8+
for (let i = 0; i < j / 2; i++) {
9+
let x = str[i];
10+
let y = str[j - i];
11+
12+
if (x != y) {
13+
return false;
14+
}
15+
}
16+
return true;
17+
}
18+
19+
function isPalindrome(str) {
20+
let ans = check_palindrome(str);
21+
22+
if (ans == true) console.log(str + " is a palindrome");
23+
else console.log(str + " not palindrome");
24+
}
25+
26+
let test = "abaaba";
27+
isPalindrome(test);
28+
29+
console.log(check_palindrome("jalaj"));
30+
}
31+
32+
// Method 2: Reversing the string
33+
34+
{
35+
function reverse(str) {
36+
let rev_str = "";
37+
for (let i = str.length - 1; i >= 0; i--) {
38+
rev_str += str[i];
39+
}
40+
41+
return rev_str;
42+
}
43+
44+
function isPalindrome(str) {
45+
reverse_str = reverse(str);
46+
47+
if (reverse_str === str) {
48+
console.log("passed string is palindrome");
49+
} else {
50+
console.log("passed string is not palindrome");
51+
}
52+
}
53+
54+
let test = "hellolleh";
55+
isPalindrome(test);
56+
}
57+
58+
// Method 3: Using the split(), reverse(), and join() Methods
59+
60+
{
61+
let check_palindrome = (str) => str === str.split("").reverse().join("");
62+
console.log(check_palindrome("hellolleh"));
63+
}
64+
65+
// Method 4: Using Array.every()
66+
67+
{
68+
function isPalindrome(str) {
69+
return str
70+
.split("")
71+
.every((char, index) => char === str[str.length - index - 1]);
72+
}
73+
74+
console.log(isPalindrome("radar"));
75+
console.log(isPalindrome("hello"));
76+
console.log(isPalindrome("level"));
77+
}
78+
79+
// Method 5: Using Two Pointers
80+
81+
{
82+
function isPalindrome(str) {
83+
let left = 0;
84+
let right = str.length - 1;
85+
86+
while (left < right) {
87+
if (str[left] !== str[right]) return false;
88+
89+
left++;
90+
right--;
91+
}
92+
93+
return true;
94+
}
95+
96+
console.log(isPalindrome("madam"));
97+
console.log(isPalindrome("test"));
98+
console.log(isPalindrome("abba"));
99+
}

0 commit comments

Comments
 (0)