文字列で最も長い単語を見つけて、それらを(重複を除いて)最大長とともに返すにはどうすればよいですか?


8

文字列内で最も長い単語を見つける方法を知っています。たとえば、このコードはここにあります。しかし、ここでの問題は、「bbbbbb」という単語が見つかったということです。彼が文字列の最初の最長の単語であるためです。その後、6文字で「ジャンプ」という単語も出てきました。私の質問は、この場合と「ジャンプした」という言葉をどのように見つけることができるかです。

更新:一意のリストが必要なので、各単語の1つのみ

function longestWord(sentence) {
  sentence = sentence.split(' ');

  let theWord = sentence[0];
  var longest = 0;
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] != "") {
      if (sentence[i].length > theWord.length) {
        longest = sentence[i].length;
        theWord = sentence[i];
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the bbbbbb lazy dog"));


sentence.filter(w => w.length === longest)その長さの単語の配列を取得してみてください。
Rafi

追加する最長の単語を保持する配列を作成してみてください。次に、filter()またはmap()を使用して長さを評価し、配列に追加できます。
CoderLee

あなたは今、ユニークな言葉で2つの答えを持っています:Yevhen'sFZs
mplungjan

回答:


9

function longestWord(sentence) {
  // First we divide the sentence into words
  var words = sentence.split(' ');
  
  // We then get the length by getting the maximun value of the length of each word
  var length = Math.max(...words.map(a=>a.length));
  return {
    length: length,
    // Finally we filter our words array returning only those of with the same length we previously calculated
    words: words.filter(i => i.length == length)
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));


1つのステートメントで長さを取得するのに最適です。.sortが配列を返さないため、さらに必要です
mplungjan

3
@LuisfelipeDejesusMunozとにかく説明を追加してみませんか?この答えを見つけた他の読者にとっては良いことです。OPに加えて。
CoderLee

@YevgenGorbunkovあなたの解決策も素晴らしいです。おかげで仲間
Trajce12

上記のソリューションは重複する単語スキップせず、実装されているアルゴリズムは不必要に配列を2回パスする必要があるため最適ではありませんが、シングルパスアプローチでは、このような短いテスト文字列でも約15%優れたパフォーマンスが得られます。
Yevgen Gorbunkov

@YevgenGorbunkovパフォーマンスは正しいですが、OPが一意の単語を取得したかどうかはわかりません(その部分は他の
ユーザー

2

シングルループアプローチを使用して、最初の項目のアキュムレータ長で各単語の長さを確認できます。

function longestWords(words) {
    return words
        .split(/\s+/)
        .reduce((accu, word) => {
            if (!accu[0] || accu[0].length < word.length) return [word];
            if (accu[0].length === word.length) accu.push(word);
            return accu;
        }, []);
}

console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));


@mplungjan:さまざまなスタイルがさまざまな人々にどのようにアピールするか興味深い。これは読みやすい答えの1つです。もちろん、多分それは私が書いた答えに似ているからかもしれませんが、ニーナが私を打ち負かしたので公開しませんでした。
Scott Sauyet

2

Array.prototype.reduce()(最大長を計算するための追加のループなしで)配列を1回パスすることでそれを行うことができます。

アイデアは、結果の配列を1つの単語でリセットすることです。その長さが、前に挿入された長さを超えるか、現在の単語が偶然同じ長さである場合は追加するか、単純に別の方法で渡します。

const src = 'The quick brown as bbbbbb fox jumped over the jumped lazy dog',

      result = src.split(' ')
                  .reduce((res, word, idx) => {
                    if(!idx || word.length > res.length)
                        res = {length: word.length, words:new Set([word])}
                    else if(word.length == res.length)
                        res.words.add(word)
                    return res
                  }, {})

console.log({result: result.length, words: [...result.words]})
.as-console-wrapper {min-height:100%}


noobが何が起こっているのかを理解できるようにするのは美徳です:)
mplungjan

このstackoverflow.com/a/60153437/295783はもっと読みやすいと思います。コメントは?
mpungjan

3
入れ子になった三項は恐ろしく危険です。シングルラインソリューションの探求は、あなたが大いに嫌いになった後でコーダーになります:)
mpungjan

複数の値を一緒に更新する(この場合はlengthwords)には、reduceはそれほど大きくないことがわかります。
Gershom

1

sentence配列を減らすことで実現できます。

このアプローチの利点は、配列を1回だけループすることです。

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words = [word]
      output.length = word.length
    } else if (word.length === output.length) {
      output.words.push(word)
    }
    return output
  }, { length: 0, words: [] })
}
console.log(longestWords("The quick brown as bbbbbb fox jumped over the lazy dog"));

または、重複する単語を除外する場合は、Set代わりにa を返すことができます。

function longestWords(sentence) {
  return sentence.split(' ').reduce((output, word) => {
    if (word.length > output.length) {
      output.words.clear()
      output.length = word.length
    } 
    if (word.length >= output.length) {
      output.words.add(word)
    }
    return output
  }, { length: 0, words: new Set })
}
const words = longestWords("The quick brown as bbbbbb fox jumped over the jumped lazy dog")
console.log(words.length);
console.log(Array.from(words.words)) //Just to make StackSnippets console show the Set's entries


これは、これまでに投稿された最も読みやすい削減です
mplungjan

一度だけ賛成できます。良い例
mplungjan

0

実行できることは、単語の長さが配列の最初の項目の長さ以上であるかどうかを確認することです(配列内のすべての項目は同じ長さでなければなりません)。

もしそうなら、それが大きいかどうかを確認してください。これがtrueの場合、配列内の単語よりも大きい単語を見つけたため、配列をその単語に設定します。それ以外の場合は、長さが最も長い単語の配列に追加します。

function longestWord(sentence) {
  sentence = sentence.split(' ');
  let theWord = sentence[0];
  var longest = 0;
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] != "") {
      if (sentence[i].length >= theWord[0].length) {
        if (sentence[i].length > theWord[0].length) {
          longest = sentence[i].length;
          theWord = [sentence[i]];
        } else {
          theWord.push(sentence[i])
        }
      }
    }
  }
  return {
    length: longest,
    actuallWord: theWord
  }
}
console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));


0

単一の削減で行うこともできます。
オブジェクトで開始されました。

function longestWord(words) {
  return words
    .split(/\s+/)
    .reduce((acc, word) => {
  	if(word.length > acc.length) {
  		acc.length = word.length;
  		acc.words = [word];
  	}
  	else if (word.length === acc.length) {
  		acc.words.push(word);
  	}
  	return acc;
  }, {length:0, words:[]});
}

console.log(longestWord("The quick brown as bbbbbb fox jumped over the lazy dog"));


0

このアプローチは、ここでの最良の回答ほど時間の複雑さはありませんが、係数は優れています。(これは単語の配列を1回ループするだけで、以外の関数呼び出しはありませんArray.prototype.push)。

let allLongestItems = items => {
  let longest = [];
  let length = 0;
  for (let item of items) {
    let len = item.length;
    if (len === length) longest.push(item)
    else if (len > length) { longest = [ item ]; length = len; }
  }
  return { items: longest, length };
};

let str = 'The quick brown as bbbbbb fox jumped over the lazy dog';
console.log(allLongestItems(str.split(' ')));

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.