简体   繁体   English

Sherlock 和 Valid String 黑客挑战

[英]Sherlock and Valid String hackerank challenge

I tried to solve this specific challenge in Hackerank and I can't pass all the test cases.我试图在 Hackerrank 中解决这个特定的挑战,但我无法通过所有测试用例。 2 is the minimum number of removals required to make it a valid string. 2 是使其成为有效字符串所需的最小删除次数。 It can be done in following two ways:可以通过以下两种方式完成:

input = aabbcd...输入 = aabbcd...

Sample Output must be no....样本输出必须是 no....

Explanation解释

Remove c and d to get aabb.删除 c 和 d 以获得 aabb。 Or remove a and b to get abcd.或者删除 a 和 b 以获得 abcd。

here is my code:这是我的代码:

function processData(input) {
    //Enter your code here
   var unique = "";
    var counter = 0;
    var different ="";
  for (i = 0; i < input.length; i++) {
    if (input.lastIndexOf(input[i]) == input.indexOf(input[i])) {
      unique += input[i];

    }counter ++;
  var count1 = (input.match(/input[i]/) || []).length;
  }
    if (counter <= 1)
    {
        console.log("YES");
    }
    else if (counter > 1){
        console.log("NO"); 
    }
    //console.log(count1);
    //console.log(unique);
}

Your algorithms is failing because your solution is not solving the problem.你的算法失败了,因为你的解决方案没有解决问题。 Your final check to see whether the String is acceptable or not uses counter最后检查字符串是否可以接受使用计数器

  if (counter <= 1)
    {
        console.log("YES");
    }
    else if (counter > 1){
        console.log("NO"); 
    }

However counter is incremented everytime your for loop runs.但是,每次 for 循环运行时,计数器都会增加。 This means your solutions is only passing the tests that resolve to "NO" by default.这意味着您的解决方案仅通过默认情况下解析为“NO”的测试。

Also your created a variable called different which you never used and both unique and count1 are assigned values but never used afterwards.您还创建了一个名为 different 的变量,您从未使用过该变量,并且 unique 和 count1 都被分配了值,但之后从未使用过。

Your algorithm should check the frequency of each string and see if they are the same (or a most different by 1) for each string.Your algorithm only checks for uniqueness of a letter.您的算法应检查每个字符串的频率,并查看每个字符串的频率是否相同(或相差最大 1)。您的算法仅检查字母的唯一性。 I would suggest counting the occurence ofeach letter using我建议使用计算每个字母的出现

input.match(/input[i]/).length;

and the comparing the frequencies和比较频率

Here is my answer.这是我的答案。 Points to remember 1. Make sure you trim else your get escape \\n as part of input.要记住的要点 1. 确保你修剪其他你的 get 转义 \\n 作为输入的一部分。 2. Count occurrences of chars. 2. 计算字符的出现次数。 3. map char count to their occurrence. 3. 将字符计数映射到它们的出现。 4. Now check if occurrence is 1 => valid else if 2 make sure you check the at least one occurrence count is 1 ex: aabbcd c and d occurs 2 times and both have char count as 1 so he has to remove both c and d. 4. 现在检查出现次数是否为 1 => 有效,否则如果 2 确保您检查至少一次出现次数为 1 例如:aabbcd c 和 d 出现 2 次且字符计数均为 1,因此他必须同时删除 c 和d.

Note: Not clarified in problem same char can be removed more than once and it still can be considered as one removal ex: aabbcccc I have 4 c's but I can use one operation to remove 2 C's to make it valid string aabbcc.注意:未在问题中澄清相同的字符可以被多次删除,它仍然可以被视为一次删除,例如:aabbcccc 我有 4 个 c,但我可以使用一个操作来删除 2 个 C 以使其成为有效的字符串 aabbcc。

var bIsValidString = false;
var oCharMapCount = input.trim().split("").reduce((acc, val) => {
    if (acc[val]) {
        acc[val] += 1;
    }
    else {
        acc[val] = 1;
    }
    return acc;
}, {});
var oCharOccuranceMap = {}; 
for(let key in oCharMapCount) {
    if (oCharOccuranceMap[oCharMapCount[key]]) {
        oCharOccuranceMap[oCharMapCount[key]] += 1;
    }
    else {
        oCharOccuranceMap[oCharMapCount[key]] = 1;
    }
}
var iCharOccurances = (Object.keys(oCharOccuranceMap) || []).length;

if (iCharOccurances === 1) {
    bIsValidString = true;
}
else if (iCharOccurances === 2) {
    for (let iCharCountOccurance in oCharOccuranceMap) {
        if (oCharOccuranceMap[iCharCountOccurance] === 1) {
            bIsValidString = true;
        }
    }
}
else {
    bIsValidString = false;
}

(bIsValidString) ? console.log("YES") : console.log("NO");

After a few iterations with 2 test cases failing, i finally came up with the correct solution below.在 2 个测试用例失败的情况下进行了几次迭代后,我终于想出了下面的正确解决方案。

//create histogram to count occurances of each char in string
let chars               = s.reduce(into: [:]) { $0[$1, default:0] += 1 }

//create set for occurances to determine the number of different occurances found
let valueSet:Set<Int> = Set(chars.values)
var isValid = false

//if all chars have same occurrance
if valueSet.count == 1 {
    isValid = true
}
//if there are more than two different occurance counts
else if valueSet.count > 2 {
    isValid = false
} 
//check different frequencies counts
else {
    
    let freq1 = valueSet.min()!
    let freq2 = valueSet.max()!
    
    var freq1Count = 0
    var freq2Count = 0
    
    //loop through all values to count the amount of times each different occurance count occur
    for value in chars.values {
        switch value {
        case freq1:
            freq1Count += 1
        default:
            freq2Count += 1
        }
    }
    
    //if either freq count is 1 and it that count only occurs once
    if (freq1 == 1 && freq1Count == 1) ||
       (freq2 == 1 && freq2Count == 1) {
        isValid = true
    }
    //if the difference between frequencies is one and there is only one of them
    else if abs(freq1 - freq2) == 1 && (freq1Count == 1 || freq2Count == 1) {
        isValid = true
    }
    else {
        isValid = false
    }
}

return isValid ? "YES" : "NO"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM