-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
Comments
function findLongestWord(str){ let str="hello world,my name is tom"; |
这个题目的说明有点模糊,单词的定义是什么?麻烦解释下 |
@Dai-Ning 当然是空格分割了。。 |
如果有多个单词一样长,只要返回随便一个的话比较简单了 @rocky-191 我觉得涉及到遍历的逻辑一般用声明式的函数会好一点,比如你的逻辑我马上就想到用reduce: const longestReducer = (pre, cur) => pre.length > cur.length ? pre : cur
const longest = array.reduce(longestReducer) |
如果有多个最长长度一样的单词,返回多个要怎么做呢? |
@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, []) |
function maxLengthString(str){
str.split('').reduce(function(start,end){
return start>end?start.length:end.length
})
} |
const str = 'aaa b cc, hello word'
str.split(/\s|,/).reduce((acc, cur) => acc > cur.length ? acc : cur.length) |
最长的单词有重复, 再统计下次数呢? |
思路还是以空格进行分割,然后对数组进行操作,多了一个对分割符的拓展。 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.")); |
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:感觉可以用正则来搞 |
function test(str){ function test1(str){ |
function getWordMaxLen(str){ } |
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')) |
function findLongestWord(str) {
var stringArr = str.split(' ')
return stringArr.reduce(function(prev, next) {
// 返回值为参数与当前字符串中较大的数
// 返回值会作为下次计算的 prev 传入
return Math.max(prev, next.length)
}, 0)
} |
|
|
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.')) |
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')) |
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)); |
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 |
// 简单易懂,略带点骚
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 };
} |
如果标准只是「用(多个)空格分割」, const maxLen = str => Math.max(...str.split(/\s+/g).map(i => i.length)) 倒是如果给一个辅助方法「判断字符串是否是合法英文单词」,把这道题理解为「在字符串中找到最长的合法英文单词」那还有点意思 |
function getLength(str) { |
|
|
'ab , cd abcde'.split(' ').reduce((pre, cur) => { |
方法一:逐字符遍历,生成单词,比较长度
/**
* @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;
});
} |
|
|
|
let strArr = str.split(' ') |
您好!我看到邮件后会立即联系您!
|
你可以通过编写一个函数来找到字符串中最长的单词,并返回其长度。以下是一个使用 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"是最长的单词) 这个函数首先使用 |
您好!我看到邮件后会立即联系您!
|
第37天 找到字符串中最长的单词,并返回它的长度
The text was updated successfully, but these errors were encountered: