找到数组中最长的非重复元素,然后返回其原始值

时间:2017-02-26 19:45:26

标签: javascript arrays loops while-loop lodash

我打算从数组中找到最长的唯一字符串(非重复字母)然后返回其原始值。

例如,在下面的数据集中

3          # Number of test cases
3          # Test case 1 has 3 names
ALFRED
SINGHHHHHH
JOHN
6          # Test case 2 has 6 names
ALPHA
NITRO
ROB
RICHARD
ANON
POPE
1          # Test case 3 has 1 name
FELIX

阿尔弗雷德,理查德和费利克斯拥有最长的独特的'名。

我的问题是我的代码返回唯一值而不是所需的原始值。

所以:

期望输出

Case #1: ALFRED
Case #2: RICHARD
Case #3: FELIX

现实

Case #1: ALFRED
Case #2: RICHAD # Notice the extra R has been removed
Case #3: FELIX

这是我正在使用的代码段:



var _ = require('lodash')
var example = '3\n3\nALFRED\nSINGHHHHH\nJOHN\n6\nALPHA\nNITRO\nROB\nRICHARD\nANON\nPOPE\n1\nFELIX';


run(example)
function run(input) {
    var lines = input.split('\n')
    var testCases = lines.shift();
    var obj = {};
    for (var i = 0; i < testCases; i++) {
        var testCase = obj[i + 1] = [];
        var numberOfNames = lines.shift();
        for (var j = 0; j < numberOfNames; j += 1) {
            let candidateNames = lines.shift()
            let strippedNames = _.uniq(candidateNames).join('')
            testCase.push(strippedNames)
        }
    }
    for (var k = 0; k < testCases; k++) {
        console.log(`Case #${[k + 1]}: ${findLongestName(obj[k + 1])}`)
        
    }
}

function findLongestName(str) {
  var longestWord = str.reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, '');
  return longestWord;
}
&#13;
&#13;
&#13;

修改

因此,在某些情况下,我们可能会获得超过1个值,这些值满足我们作为最长唯一值的条件(它们都具有相同的长度)。在这种情况下,我们需要选择按字母顺序排列的第一个!

例如:

3          # Number of test cases
3          # Test case 1 has 3 names
CKLGNTVKPJUQVHFKOJYC
ZSQXRMZYDOAICOQHPYHU
JOHN
6          # Test case 2 has 6 names
ALPHA
NITRO
ROB
RICHARD
ANON
POPE
1          # Test case 3 has 1 name
FELIX

在上面的示例中,'CKLGNTVKPJUQVHFKOJYC'应该是所选的。

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function run(input) {
  var lines = input.split('\n');
  var testCases = lines.shift();
  var result = {};
  for (var i = 0; i < testCases; i++) {
    var hash = {};                                  // an hash object for the lengths of this test case (see explanation bellow)
    var numberOfNames = lines.shift();              // the number of names in this test case
    for (var j = 0; j < numberOfNames; j += 1) {    // for each name in this test case
      let name = lines.shift();                     // get the name
      let length = _.uniq(name).length;             // get its unique length (the length of its unique characters)
      if (hash[length])                             // if we laready hashed this length
        hash[length].push(name);                    // then push this original name to the according array
      else                                          // if we haven't
        hash[length] = [name];                      // then create a new array for this length (initially containing this name)
    }
    //console.log(hash);
    var max = Math.max.apply(null, Object.keys(hash)); // get the max length from the hash object (the lengths are the keys of the hash object)
    //console.log(max);
    result["Test Case " + (i + 1)] = hash[max];     // store the array for that length as the result of this test case
  }
  return result;
}

var example = '3\n3\nALFRED\nSINGHHHHH\nJOHN\n6\nALPHA\nNITRO\nROB\nRICHARD\nANON\nPOPE\n1\nFELIX';

var result = run(example);

console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;

<强>解释

例如,如果用例是:

ALFRED
SINGHHHHHH
JOHN
BANANA

对于测试用例中的每个名称,我们得到其唯一字符的长度(上例中的长度为654和{{1} } 分别)。然后我们将具有相同长度的名称存储到一个数组中,并将该数组存储在一个长度为key的哈希对象中,因此上面示例的哈希对象将如下所示:

6

然后我们得到数组键中的最大长度(示例中为hash = { 6: ["ALFRED", "BANANA"], 5: ["SINGHHHHHH"], 4: ["JOHN"] } ),然后我们将等效数组(6)存储为此测试用例的结果。

修改

如果您只想选择出现的第一个,请更改此行:

["ALFRED", "BANANA"]

为:

result["Test Case " + (i + 1)] = hash[max];    // instead of pushing the whole array

答案 1 :(得分:1)

这不是一个非常友好的数据结构,但您仍可以在功能上执行以下操作;

&#13;
&#13;
function doSomething(s){
  return s.split("\n")
          .slice(1) // throw away the useless first information
          .reduce((r,c,i,a) => Number.isInteger(+c) ? (r.push(a.slice(i+1,+c+i+1)),r) : r, [])
          .map(g => g.map(s => Array.prototype.reduce.call(s, function(r,c){
                                                                c === r[r.length-1] && (r.stop = true);
                                                                !r.stop && r.push(c);
                                                                return r;
                                                              },[])
                                              .join(""))
                     .reduce((p,c) => p.length > c.length ? p : c));
}
var data = '3\n3\nALFRED\nSINGHHHHH\nJOHN\n6\nALPHA\nNITRO\nROB\nRICHARD\nANON\nPOPE\n1\nFELIX';

console.log(doSomething(data));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

下面的解决方案使用times迭代并返回每个测试用例的每个最长的非重复字符串。它的回调函数使用lines数组(通过\n分割输入字符串获得)来获得splice的每种情况下的所有字符串。拼接后,我们使用sortBy按照其唯一长度(字符串中的非重复字符)对每个字符串进行排序。最后,我们在数组中得到last字符串。

function getResult(input) {
  var lines = input.split('\n');
  return _.times(lines.shift(), () => {
    return _(lines)
      .splice(0, lines.shift())
      .sortBy(item => _(item).uniq().size())
      .last();
  });
}

var input = '3\n3\nALFRED\nSINGHHHHH\nJOHN\n6\nALPHA\nNITRO\nROB\nRICHARD\nANON\nPOPE\n1\nFELIX';

function getResult(input) {
  var lines = input.split('\n');
  return _.times(lines.shift(), () => {
    return _(lines)
      .splice(0, lines.shift())
      .sortBy(item => _(item).uniq().size())
      .last();
  });
}

console.log(getResult(input));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

更新:如果唯一性相同,我们可以使用map将每个项目转换为[<unique length>, <string>]的数组合成,并将此合成用于order每个项目按其唯一长度(索引0)按升序排列,其各自的字符串(索引1)按降序排列。最后,我们再次使用map来获取所有字符串(索引1)。

function getResult(input) {
  var lines = input.split('\n');
  return _.times(lines.shift(), () => {
    return _(lines)
      .splice(0, lines.shift())
      .map(item => [_(item).uniq().size(), item])
      .orderBy([0, 1], ['asc', 'desc'])
      .map(1)
      .last();
  });
}

注意:我添加了ALBERTCKLGNTVKPJUQVHFKOJYCZSQXRMZYDOAICOQHPYHU

var input = '3\n6\nCKLGNTVKPJUQVHFKOJYC\nZSQXRMZYDOAICOQHPYHU\nALFRED\nALBERT\nSINGHHHHH\nJOHN\n6\nALPHA\nNITRO\nROB\nRICHARD\nANON\nPOPE\n1\nFELIX';

function getResult(input) {
  var lines = input.split('\n');
  return _.times(lines.shift(), () => {
    return _(lines)
      .splice(0, lines.shift())
      .map(item => [_(item).uniq().size(), item])
      .orderBy([0, 1], ['asc', 'desc'])
      .map(1)
      .last();
  });
}

console.log(getResult(input));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>