Home >Web Front-end >JS Tutorial >Find minimal deletions in string in JavaScript

Find minimal deletions in string in JavaScript

WBOY
WBOYforward
2023-08-25 11:57:021215browse

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

Suppose we have a binary string like this -

const str = '001001';

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;

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));

Output

The output in the console will be -

2

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete