Skip to content

[js] 第37天 找到字符串中最长的单词,并返回它的长度 #138

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第37天 找到字符串中最长的单词,并返回它的长度

Activity

rocky-191

rocky-191 commented on May 23, 2019

@rocky-191

function findLongestWord(str){
// let arr=str.split(" ");
let arr=str.replace(/[,|.|;]/," ").split(" ");
let longLength=0,word;
for(let i=0;i<arr.length;i++){
if(arr[i].length>longLength){
word=arr[i];
longLength=arr[i].length;
}
}
return {
longLength,word
};
}

let str="hello world,my name is tom";
console.log(findLongestWord(str).longLength,findLongestWord(str).word);

ghost

ghost commented on May 23, 2019

@ghost

这个题目的说明有点模糊,单词的定义是什么?麻烦解释下

tzjoke

tzjoke commented on May 28, 2019

@tzjoke

@Dai-Ning 当然是空格分割了。。

tzjoke

tzjoke commented on May 28, 2019

@tzjoke

如果有多个单词一样长,只要返回随便一个的话比较简单了
第一想法是split成数组,然后sort函数来排序,返回arr[0]及其length

@rocky-191 我觉得涉及到遍历的逻辑一般用声明式的函数会好一点,比如你的逻辑我马上就想到用reduce:

const longestReducer = (pre, cur) => pre.length > cur.length ? pre : cur
const longest = array.reduce(longestReducer)
Samuel-world

Samuel-world commented on Jun 2, 2019

@Samuel-world

如果有多个最长长度一样的单词,返回多个要怎么做呢?

tzjoke

tzjoke commented on Jun 2, 2019

@tzjoke

@Samuel-world 还用reduce的思路,保存的是数组就行了

const longestReducer = (pre, cur) => {
    if (!pre.length || pre[0].length < cur.length) return [cur]
    if (pre[0].length === cur.length) {
        pre.push(cur)
        return pre
    } 
    return pre
}
const longest = array.reduce(longestReducer, [])
myprelude

myprelude commented on Jun 13, 2019

@myprelude
function maxLengthString(str){
 str.split('').reduce(function(start,end){
   return start>end?start.length:end.length
 })
}
think2011

think2011 commented on Jun 17, 2019

@think2011
const str = 'aaa b cc, hello word'
str.split(/\s|,/).reduce((acc, cur) => acc > cur.length ? acc : cur.length)
Kntt

Kntt commented on Jul 9, 2019

@Kntt

如果有多个最长长度一样的单词,返回多个要怎么做呢?

最长的单词有重复, 再统计下次数呢?

Konata9

Konata9 commented on Jul 11, 2019

@Konata9

思路还是以空格进行分割,然后对数组进行操作,多了一个对分割符的拓展。

const getLongestWord = (str, sperator = " ") => {
  if (!str) {
    return str;
  }

  let longestWord = {
    len: 0,
    word: ""
  };

  str
    .replace(/[,\.;]/g, "")
    .split(sperator)
    .forEach(word => {
      const { len } = longestWord;
      if (word.length > len) {
        longestWord = {
          len: word.length,
          word
        };
      }
    });
  return longestWord;
};

console.log(getLongestWord("I have an apple."));
console.log(getLongestWord("I have a pen."));
Vi-jay

Vi-jay commented on Jul 29, 2019

@Vi-jay
function maxWords(str) {
  const wordsGroup = str.split("")
    .reduce((map, cur) => map.set(cur, map.has(cur) ? map.get(cur) + 1 : 0), new Map());
  return [...wordsGroup.entries()].reduce((pre, cur) => {
    return pre[1] > cur[1] ? pre : cur
  })[0]
}

ps:感觉可以用正则来搞

seho-dev

seho-dev commented on Sep 4, 2019

@seho-dev

function test(str){
// 根据空格分隔
str = str.split(" ");
return str.reduce((start,end) => {
return start.length >= end.length? start: end
})
}

function test1(str){
// 根据空格分隔
str = str.split(" ");
return str.sort((first,end) => {
if(first.length < end){
return first < end
}else{
return first > end
}
})
}

fanqingyun

fanqingyun commented on Sep 6, 2019

@fanqingyun

function getWordMaxLen(str){
return Math.max(... str.match(/\b[a-zA-z]+\b/g).map(item => {
return item.length
}))

}

JJL-SH

JJL-SH commented on Sep 18, 2019

@JJL-SH
function findMax(str) {
  return str.split(" ").reduce(
    (cacheWord, it) => {
      if (it.length > cacheWord.length) {
        cacheword = {
          length: it.length,
          word: it
        };
      }

      return cacheword;
    },
    { length: 0, word: "" }
  );
}
console.log(findMax('123 1234 123456 123'))

7 remaining items

rni-l

rni-l commented on Jan 16, 2020

@rni-l
function getMaxLen(str) {
  const array = str.match(/\b[a-zA-Z]+\b/g)
  return array.reduce((acc, cur) => {
    if (cur.length > acc.length) return cur
    return acc
  }, '')
}

console.log(getMaxLen('sdfn hdo fjqw hqfweoubhr oiqwehuio rhqweouihr pqwep hpidofj jdfsdjfp ojep jfpej 134 5134 31 e geg dfg df g')) // hqfweoubhr
Seastyle

Seastyle commented on Mar 7, 2020

@Seastyle
// 简单易懂,略带点骚

function getMostLength(str) {
   if (!str) return;
   const arr = str.split(' ');
   let itemLengthArr = [];
   arr.forEach(item => {
      itemLengthArr.push(item.length);
   });

   const max = Math.max(...itemLengthArr);
   return { item: arr[itemLengthArr.indexOf(max)], length: max };
}
gaoryrt

gaoryrt commented on Mar 9, 2020

@gaoryrt

如果标准只是「用(多个)空格分割」,
不知道这题难度在哪里:

const maxLen = str => Math.max(...str.split(/\s+/g).map(i => i.length))

倒是如果给一个辅助方法「判断字符串是否是合法英文单词」,把这道题理解为「在字符串中找到最长的合法英文单词」那还有点意思

c37csq

c37csq commented on May 20, 2020

@c37csq

function getLength(str) {
if (!str) return;
const strArr = str.split(' ');
let info = {}
strArr.forEach(item => {
if (JSON.stringify(info) === '{}') {
info.value = item
info.length = item.length
} else {
if (item.length > info.length) {
info.value = item
info.length = item.length
}
}
})
return info
}

adi0754

adi0754 commented on Jun 12, 2020

@adi0754
'ab , cd  abcde'.match(/[a-z]+/gi).reduce((pre,cur)=>pre.length<cur.length ? cur : pre, '');
blueRoach

blueRoach commented on Jul 8, 2020

@blueRoach
function maxStr(str){
  return str.split(' ').reduce((a, b) => {
    if(a && b){
      if(a.length > b.length){
        return a
      }else{
        return b
      }
    }
  })
}
Alex-Li2018

Alex-Li2018 commented on Aug 11, 2020

@Alex-Li2018

'ab , cd abcde'.split(' ').reduce((pre, cur) => {
console.log(pre, cur);
return pre.length > cur.length ? pre : cur
}, '')

CoderLeiShuo

CoderLeiShuo commented on Aug 14, 2020

@CoderLeiShuo

方法一:逐字符遍历,生成单词,比较长度

  • 缺点:不适用含有标点符号的英文字符串
/**
 * @description: 查找英文字符串中最长的单词,并返回它的长度
 * @param {str} string 英文字符串 
 * @return {number} 
 */
function findLongestWordLength(str) {
    let longestWord = "";
    let currentWord = "";

    //逐字母遍历
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) === " ") { //当前字符是空格
            if (currentWord.length > longestWord.length) longestWord = currentWord; //检查该单词是否是最长的单词
            currentWord = ""; //清除当前单词
        } else {
            currentWord += str.charAt(i); //非空格字符,添加该字符继续创建单词
        }
    }
    if (currentWord > longestWord) longestWord = currentWord; //到达字符串末尾,再次检查当前单词是否是最长的单词
    return longestWord;
}

const longest = findLongestWordLength("The quick brown fox jumped over the lazy dog");
console.log(longest);

方法二:通过split()方法进行分割单词

  • 缺点:不适用于含有标点符号的英文字符串
let str = 'Thank you for your company over the years, you are my best friend and love you!';

function findLongestWord(str) {
    if (typeof str !== 'string') return false;
    const arr = str.split(' ');
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
        max = max.length > arr[i].length ? max : arr[i];
    }
    console.log(max);
}

方法三:通过math()方法进行分隔

  • 优点:适用于含有标点符号的英文字符串
let str = 'Thank you for your company over the years, you are my best friend and love you!';
function findLongestWord(str) {
    if (typeof str !== 'string') return false;
    const matchArr = str.match(/[a-zA-Z]+/gi);
    return matchArr.reduce((acc, cur) => {
        if (acc.length > cur.length) return acc;
        return cur;
    });
}
laboonly

laboonly commented on Aug 31, 2020

@laboonly
function spStr(str) {
  const str2 = str.replace(/[,|.|;]/, " ")
  const arr = str2.split(" ");
  const longstReducer = (pre, cur) => pre.length > cur.length ? pre : cur
  const longest = arr.reduce(longstReducer)
  return  longest.length
}

smile-2008

smile-2008 commented on Oct 26, 2020

@smile-2008

思路还是以空格进行分割,然后对数组进行操作,多了一个对分割符的拓展。

const getLongestWord = (str, sperator = " ") => {
  if (!str) {
    return str;
  }

  let longestWord = {
    len: 0,
    word: ""
  };

  str
    .replace(/[,\.;]/g, "")
    .split(sperator)
    .forEach(word => {
      const { len } = longestWord;
      if (word.length > len) {
        longestWord = {
          len: word.length,
          word
        };
      }
    });
  return longestWord;
};

console.log(getLongestWord("I have an apple."));
console.log(getLongestWord("I have a pen."));

.replace(/[,\.;]/g, " ")

codelo-99

codelo-99 commented on Dec 4, 2021

@codelo-99

const getLongWordLength = (text) => [...text.match((/([a-z]+)/gi))].reduce((pre, cur) => Math.max(pre, cur.length), 0)

xiaoqiangz

xiaoqiangz commented on Jun 1, 2022

@xiaoqiangz

let strArr = str.split(' ')
return strArr.reduce((pre, cur) => {
return pre.length > cur.length ? pre : cur
}, 0)

CoderLeiShuo

CoderLeiShuo commented on Oct 11, 2022

@CoderLeiShuo
an31742

an31742 commented on Nov 23, 2023

@an31742

你可以通过编写一个函数来找到字符串中最长的单词,并返回其长度。以下是一个使用 JavaScript 的示例:

function findLongestWordLength(str) {
  // 将字符串分割成单词数组
  var words = str.split(' ');

  // 初始化最长单词长度
  var maxLength = 0;

  // 遍历单词数组,更新最长单词长度
  for (var i = 0; i < words.length; i++) {
    // 移除单词中的标点符号等非字母字符
    var cleanWord = words[i].replace(/[^a-zA-Z]/g, '');

    // 更新最长单词长度
    if (cleanWord.length > maxLength) {
      maxLength = cleanWord.length;
    }
  }

  return maxLength;
}

// 示例用法
var sentence = "The quick brown fox jumps over the lazy dog.";
var result = findLongestWordLength(sentence);
console.log(result);  // 输出:6(因为"jumps"是最长的单词)

这个函数首先使用 split(' ') 将字符串分割成单词数组,然后通过一个循环遍历数组中的每个单词,使用 replace 方法去除单词中的标点符号等非字母字符,最后比较单词的长度并更新最长单词长度。

CoderLeiShuo

CoderLeiShuo commented on Nov 23, 2023

@CoderLeiShuo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smile-2008@think2011@haizhilin2013@gaoryrt@JJL-SH

        Issue actions

          [js] 第37天 找到字符串中最长的单词,并返回它的长度 · Issue #138 · haizlin/fe-interview