user7597670
user7597670

Reputation:

find added characters to string js

I have two strings, the second is the same as the first but with three added characters somewhere in the string (three of the same characters)

example below:

string1 = "hello"
string2 = "aaahello"

// => 'a'

The characters could be anywhere in the string. Another example

string1 = "abcde"
string2 = "2db2a2ec"

// => '2'

There is one more caveat in that the added character could also exist among the original string

string1 = "aabbcc"
string2 = "aacccbbcc"

// => 'c'

I have tried the following, but this doesn't give me the three identical characters that have been added to the second string. I cannot figure out how to find the three added identical characters:

function addedChar(a, b){
    var i = 0;
    var j = 0;
    var result = "";

    while (j < b.length)
    {
        if (a[i] != b[j] || i == a.length)
            result += b[j];
        else
            i++;
        j++;
    }


    return result;
}

Upvotes: 2

Views: 164

Answers (3)

pethel
pethel

Reputation: 5537

What bout this? This goes just one way but you can do it both ways.

string1 = "aabbcc";
string2 = "aacccbbcc";
diff = string2;

for(let i = 0; i < string1.length; i++) {
  const char = string1[i];
  diff = diff.replace((new RegExp(`${char}`)), '');
}

//ccc
console.log(diff);

Upvotes: 2

marzelin
marzelin

Reputation: 11600

function findAddedChars(string1, string2) {
  return string1.split("").reduce((s2, char) => {
    const index = s2.indexOf(char)
    return s2.slice(0, index).concat(s2.slice(index + 1))
  }, string2.split("")).join("")[0]
}

let string1
let string2

string1 = "hello"
string2 = "aaahello"
console.log(findAddedChars(string1, string2)) // => 'a'

string1 = "abcde"
string2 = "2db2a2ec"
console.log(findAddedChars(string1, string2))  // => '2'

string1 = "aabbcc"
string2 = "aacccbbcc"
console.log(findAddedChars(string1, string2)) // => 'c'

Upvotes: 0

juvian
juvian

Reputation: 16068

Efficient solution:

var string1 = "aabbcc"
var string2 = "aacccbbcc"

function charCount (str) {
  var count = {};
  for (var i = 0; i < str.length; i++) {
      count[str[i]] = (count[str[i]] || 0) + 1; 
  }
  return count;
}

var count1 = charCount(string1);
var count2 = charCount(string2);

console.log(Object.keys(count2).filter(char => count2[char] != count1[char])[0]);

Upvotes: 0

Related Questions