Code. Money. Travel.
Home

Palindrome

Published in Code
July 02, 2022
1 min read
Palindrome

Palindrome adalah suatu kata, frasa, angka, maupun susunan lainnya apabila dibaca dari depan atau belakang bunyinya tetap sama. contoh: katak, malam, ini.

Coding Interview Series:

  1. Palindrome


Simple Way

const isPalindrome = (str) => {
  return str === str
    .split("")
    .reverse()
    .join("");
}

Without JavaScript Function

const isPalindrome = (str) => {
  let temp = '';

  for (let i = str.length - 1; i >= 0; i--) {
    temp = temp + str.charAt(i)
  }

  return str === temp;
}

Without Temp Variable

const isPalindrome = (str) => {

  for (let i = 0; i < str.length; i++) {

  // or you can simplify by only check a half of str length.
  // for (let i = 0; i < str.length; i++) {

    const indexStart = i;
    const indexEnd = str.length - i - 1;

    if (str.charAt(indexStart) !== str.charAt(indexEnd)) {
      return false;
    }
  }

  return true;
};

Without Looping, Use Recursive

const isPalindromeRecursive = (str, i) => {
  if (i < str.length / 2) {
    const indexStart = i;
    const indexEnd = str.length - i - 1;

    if (str.charAt(indexStart) !== str.charAt(indexEnd)) {
      return false;
    } else {
      return isPalindromeRecursive (str, i+1);
    }
  } else {
    return true;
  }
}

const isPalindrome = (str) => {
  return isPalindromeRecursive(str, 0);
};



source:
https://youtu.be/DXQuiPKl79Y


Tags

#coding-interview
Previous Article
Membuat Todo List dengan React dan Firebase

Topics

Code
Money
Travel

Related Posts

Optimize Database Query in Laravel
August 06, 2022
1 min
© 2024, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media