- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Forming palindrome using at most one deletion in JavaScript
Problem
We are required to write a JavaScript function that takes in a string, str, as the first and the only argument.
Our function may delete at most one character from the string str and we are required to check whether we can make it a palindrome doing so.
For example, if the input to the function is
Input
const str = 'dr.awkward';
Output
const output = true;
Output Explanation
Because if we delete ‘.’ from the string,
Example
Following is the code −
const str = 'dr.awkward'; const validPalindrome = (str = '') => { const valid = (left, right) => { for (let i = left; i <= Math.floor((left + right) / 2); i++) { if (str[i] !== str[right - (i - left)]) { return false } } return true } for (let i = 0; i <= Math.floor(str.length / 2); i++) { const right = str.length - 1 - i if (str[i] !== str[right]) { return valid(i, right - 1) || valid(i + 1, right) } } return true } console.log(validPalindrome(str));
Output
true
Advertisements