Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
haizhilin2013 opened this issue May 22, 2019 · 36 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the js JavaScript label May 22, 2019
@rocky-191
Copy link

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
Copy link

ghost commented May 23, 2019

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

@tzjoke
Copy link

tzjoke commented May 28, 2019

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

@tzjoke
Copy link

tzjoke commented May 28, 2019

如果有多个单词一样长,只要返回随便一个的话比较简单了
第一想法是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
Copy link

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

@tzjoke
Copy link

tzjoke commented Jun 2, 2019

@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
Copy link

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

@think2011
Copy link

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

@Kntt
Copy link

Kntt commented Jul 9, 2019

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

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

@Konata9
Copy link

Konata9 commented Jul 11, 2019

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

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
Copy link

Vi-jay commented Jul 29, 2019

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
Copy link

seho-dev commented Sep 4, 2019

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
Copy link

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

}

@JJL-SH
Copy link

JJL-SH commented Sep 18, 2019

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'))

@ZindexYG
Copy link

function findLongestWord(str) {
  var stringArr = str.split(' ')

  return stringArr.reduce(function(prev, next) {
    // 返回值为参数与当前字符串中较大的数
    // 返回值会作为下次计算的 prev 传入
    return Math.max(prev, next.length)
  }, 0)
}

@jinweiya0507
Copy link

@wiseal2
Copy link

wiseal2 commented Oct 16, 2019

const getLongestStr = (str) => {
	const res = str.split(/[^\w]/).reduce((acc, next) => {
		(next.length > acc._length) && (acc._length = next.length, acc.str = next)
		return acc;
	}, { str: '', _length: 0 });
	return res;
}
console.log(getLongestStr('i have items,please call me!!!!!!!!!'));
//{str: "please", _length: 6}

@censek
Copy link

censek commented Nov 5, 2019

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

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, " ")

@canwdev
Copy link

canwdev commented Nov 7, 2019

function findLongestWord(str) {
    if (!str) return str
    
    str = str.replace(/[,\.]/g, '')
    const words = str.split(' ')
    const sortedWords = words.sort((a,b) => b.length - a.length)

    return sortedWords[0]
}

console.log(findLongestWord('I have a apple, I have a pen, duang, applepen.'))

@diandianzd
Copy link

function maxStrStr(str) {
  let res = ''
  str.split(' ').forEach(item => {
    console.log(item.length > res.length)
    if (item.length > res.length) {
      res = item
    }
  })
  return res
}

console.log(maxStrStr('a bc def ab'))

@YeChang
Copy link

YeChang commented Dec 24, 2019

const str = "aaa b cc, hello word";

function LongestWord(str) {
  str = str.replace(/[^a-zA-Z0-9\s]/g, "");

  return str.split(" ").sort((a, b) => {
    return b.length - a.length;
  })[0];
}
console.log(LongestWord(str));

@rni-l
Copy link

rni-l commented Jan 16, 2020

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
Copy link

Seastyle commented Mar 7, 2020

// 简单易懂,略带点骚

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
Copy link

gaoryrt commented Mar 9, 2020

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

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

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

@c37csq
Copy link

c37csq commented May 20, 2020

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
}

@13168335674
Copy link

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

@blueRoach
Copy link

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

@Alex-Li2018
Copy link

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

@CoderLeiShuo
Copy link

CoderLeiShuo commented Aug 14, 2020

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

  • 缺点:不适用含有标点符号的英文字符串
/**
 * @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
Copy link

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
}

@MrZ2019
Copy link

MrZ2019 commented Oct 26, 2020

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

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
Copy link

codelo-99 commented Dec 4, 2021

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

@xiaoqiangz
Copy link

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

@CoderLeiShuo
Copy link

CoderLeiShuo commented Oct 11, 2022 via email

@an31742
Copy link

an31742 commented Nov 23, 2023

你可以通过编写一个函数来找到字符串中最长的单词,并返回其长度。以下是一个使用 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
Copy link

CoderLeiShuo commented Nov 23, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests