Home > Web Front-end > JS Tutorial > body text

Find minimal deletions in string in JavaScript

WBOY
Release: 2023-08-25 11:57:02
forward
1186 people have browsed it

在 JavaScript 中查找字符串中的最少删除

Suppose we have a binary string like this -

const str = '001001';
Copy after login

We need to write a JavaScript function that accepts a string like this as the first and also The only parameter.

The function should then calculate and return the minimum number of deletions required in the input so that no two adjacent numbers are the same.

For example, for the above string, the output should be -

const output = 2;
Copy after login

Because if we remove "0" at index 0 and 3, the new string will be "0101", which is The longest string required.

Example

This code will be -

Live Demo

const str = '001001';
const minimumDeletions = (str = '') => {
   let count = 0;
   const { length } = str;
   for(let i = 0; i < length; i++){
      if (str[i] === str[i + 1]){
         count++;
      };
   }
   return count;
};
console.log(minimumDeletions(str));
Copy after login

Output

The output in the console will be -

2
Copy after login

The above is the detailed content of Find minimal deletions in string in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!