Knowledge Base (Advanced Level Coding Questions and Answers)

Please review knowledge base, if you cannot find the answer you are looking for? Reach out to our support team by opening forum thread.

1. Write a function in React that converts a given string?

Input: "aaabbcccdd" Output: "3a2b3c2d"

// Solution 1:
function compressString(input) {
  let result = '';
  let count = 1;

  for (let i = 1; i <= input.length; i++) {
    if (input[i] === input[i - 1]) {
      count++;
    } else {
      result += count + input[i - 1];
      count = 1;
    }
  }

  return result;
}

const inputString = "aaabbcccdd";
const compressedString = compressString(inputString);
console.log(compressedString); // Output: "3a2b3c2d"

 

// Solution 2:
import React from 'react';

class StringCompressor extends React.Component {
  compressString(input) {
    let compressedString = '';
    let count = 1;

    for (let i = 1; i < input.length; i++) {
      if (input[i] === input[i - 1]) {
        count++;
      } else {
        compressedString += count + input[i - 1];
        count = 1;
      }
    }

    // Handle the last set of consecutive characters
    compressedString += count + input[input.length - 1];

    return compressedString;
  }

  render() {
    const inputString = 'aaabbcccdd';
    const compressedString = this.compressString(inputString);

    return (
      <div>
        Input: {inputString}
        <br />
        Output: {compressedString}
      </div>
    );
  }
}

export default StringCompressor;