找到字符串js的添加字符

时间:2017-07-24 17:54:13

标签: javascript

我有两个字符串,第二个与第一个字符串相同,但字符串中有三个添加的字符(三个相同的字符)

以下示例:

string1 = "hello"
string2 = "aaahello"

// => 'a'

字符可以是字符串中的任何位置。 另一个例子

string1 = "abcde"
string2 = "2db2a2ec"

// => '2'

还有一点需要注意的是,添加的字符也可能存在于原始字符串

string1 = "aabbcc"
string2 = "aacccbbcc"

// => 'c'

我尝试过以下操作,但这并没有给我添加到第二个字符串的三个相同字符。我无法弄清楚如何找到三个相同的字符:

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

3 个答案:

答案 0 :(得分:2)

这是什么回事?这只是一种方式,但你可以两种方式。

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

答案 1 :(得分:0)

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'

答案 2 :(得分:0)

高效的解决方案:

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