有没有一种简洁的方法来查找字符串数组中最长的字符串?
类似于arr.Max(x => x.Length);
这样的东西?
自 Javascript 1.8/ECMAScript 5 起可用,并且大多数旧版浏览器也支持 reduce 方法:
var longest = arr.reduce(
function (a, b) {
return a.length > b.length ? a : b;
}
);
否则,一个安全的替代方案:
var longest = arr.sort(
function (a, b) {
return b.length - a.length;
}
)[0];
一道老问题的新解: 在ES6中你可以使用更简洁的写法:
Math.max(...(x.map(el => el.length)));
O(n^2)
,而其他大多数选项只需遍历一次集合即可达到O(n)
的复杂度。使用 sort
的自定义比较器甚至可以达到O(log(n))
的复杂度。 - CTS_AEO(n) + O(n) = O(n)
,而不是 O(n^2)
。 - Joshua Breeden我会这样做
var arr = [
'first item',
'second item is longer than the third one',
'third longish item'
];
var lgth = 0;
var longest;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > lgth) {
var lgth = arr[i].length;
longest = arr[i];
}
}
console.log(longest);
var lgth
吗?如果不重新声明lgth
,这样做会给我正确的答案。但是,在我的版本中,我将所有的var
都改成了let
。 - HappyHands31function findLongestWord(array) {
var longestWord = "";
array.forEach(function(word) {
if(word.length > longestWord.length) {
longestWord = word;
}
});
return longestWord;
}
var word = findLongestWord(["The","quick","brown", "fox", "jumped", "over", "the", "lazy", "dog"]);
console.log(word); // result is "jumped"
自IE9+开始,数组函数forEach已被支持。
reduce()
方法以 O(n)
的时间复杂度来实现这一点,而不是使用 sort()
方法,其时间复杂度为 O(nlogn)
。
const getLongestText = (arr) => arr.reduce(
(savedText, text) => (text.length > savedText.length ? text : savedText),
'',
);
console.log(getLongestText(['word', 'even-longer-word', 'long-word']))
arr.reduce(function(savedText, text) { return text.length > savedText.length ? text : savedText; }, '');
- maxshutyvar arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];
这里 input
是一个字符串数组
function Max(input) {
return input.reduce((a, b) => a.length <= b.length ? b : a)
}
function timo_longest(a) {
var c = 0, d = 0, l = 0, i = a.length;
if (i) while (i--) {
d = a[i].length;
if (d > c) {
l = i; c = d;
}
}
return a[l];
}
arr=["First", "Second", "Third"];
var longest = timo_longest(arr);
我提供了一种功能性+递归的方法。看看注释以了解它是如何工作的:
const input1 = ['a', 'aa', 'aaa']
const input2 = ['asdf', 'qwer', 'zxcv']
const input3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf']
const input4 = ['ddd', 'dddddddd', 'dddd', 'ddddd', 'ddd', 'dd', 'd', 'd', 'dddddddddddd']
// Outputs which words has the greater length
// greatestWord :: String -> String -> String
const greatestWord = x => y =>
x.length > y.length ? x : y
// Recursively outputs the first longest word in a series
// longestRec :: String -> [String] -> String
const longestRec = longestWord => ([ nextWord, ...words ]) =>
// ^^^^^^^^^^^^
// Destructuring lets us get the next word, and remaining ones!
nextWord // <-- If next word is undefined, then it won't recurse.
? longestRec (greatestWord (nextWord) (longestWord)) (words)
: longestWord
// Outputs the first longest word in a series
// longest :: [String] -> String
const longest = longestRec ('')
const output1 = longest (input1)
const output2 = longest (input2)
const output3 = longest (input3)
const output4 = longest (input4)
console.log ('output1: ', output1)
console.log ('output2: ', output2)
console.log ('output3: ', output3)
console.log ('output4: ', output4)
使用ES6并支持重复字符串
var allLongestStrings = arrayOfStrings => {
let maxLng = Math.max(...arrayOfStrings.map( elem => elem.length))
return arrayOfStrings.filter(elem => elem.length === maxLng)
}
let arrayOfStrings = ["aba", "aa", "ad", "vcd","aba"]
console.log(allLongestStrings(arrayOfStrings))
reduce
。 - deceze