[removed] find longest word in a string

前端 未结 30 2546
余生分开走
余生分开走 2020-11-27 03:50
function longestWord(string) {
    var str = string.split(\" \");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
                


        
相关标签:
30条回答
  • 2020-11-27 04:10
    function longestWord(sentence){
     var arr = sentence.match(/[a-z]+/gi);
     arr.sort(function(a, b){
     return b.length - a.length;
    });
     return arr[0];
    }
    longestWord('hello man@#$%');
    // ==> output: hello
    
    0 讨论(0)
  • 2020-11-27 04:11

    The index is going up to str.length -1:

    for (var i = 0; i < str.length - 1; i++) {
    

    So the last word is not processed.

    Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA).

    In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.

    for (var i = 0; i < str.length; i++) {
    

    Check a demo with both versions (the problematic and the fixed): link here.

    0 讨论(0)
  • 2020-11-27 04:12

    You have a -1 in your condition, it never even scans it:

    for (var i = 0; i < str.length - 1; i++) {
    

    Should be:

    for (var i = 0; i < str.length; i++) {
    

    Demo: http://jsfiddle.net/LfgFk/

    0 讨论(0)
  • 2020-11-27 04:13
    function LongestWord(sen) { 
    
      // code goes here  
      const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
      wordsArray.sort((a, b) => a.length < b.length);
      return wordsArray[0]; 
    
    }
    
    0 讨论(0)
  • 2020-11-27 04:14
    function longestWord(string) {
       var str = string.split(" ");
       var longest = 0;
       var word = null;
       for (var i=0; i < str.length-1; i++) {
          word = longest < str[i].length ? str[i].length : longest;
             word = str[i];
       }
       return word;
       }
       longestWord('I love Python ')
    
    0 讨论(0)
  • 2020-11-27 04:15

    solutions are incomplete. what if there r 2 or more words that have same length. here is a better solution:

    longest = str => {
      let words = str.split(" ");
      let size = 0;
      let max = [""];
    
      for (let i = 0; i < words.length; i++) {
        if (words[i].length > size) {
          size = words[i].length;
        }
        if (max[max.length - 1].length < words[i].length) {
          max = [];
          max.push(words[i]);
        } else {
          max = [...max, words[i]];
        }
      }
      return max;
    };
    
    0 讨论(0)
提交回复
热议问题