[英]Find longest word in Javascript array
因此,我正在解決此Codility編碼挑戰,而我無法使代碼適用於所有輸入,尤其是大型輸入。 規則在這里 。
總而言之,我需要測試字符串中的每個單詞:僅字母數字字符,偶數字母和奇數位數。
對於示例輸入-“ test 5 a0A pass007?xy1”,此解決方案有效地忽略了“ test”(它具有偶數位數,0位數字)和“?xy1”(特殊字符,?)。 從剩余的選項中,它選擇pass007作為最長的單詞,並返回7(單詞長度)。
我首先將字符串拆分為單獨的單詞,然后生成if語句以檢查新數組中的每個單詞是否滿足要求,即isAlpha,isAlphaEven(對於偶數個字母,其余為0),isNumeric(對於奇數個位數,為1)。
知道我在做什么錯嗎? 非常感謝! :)
// you can write to stdout for debugging purposes,
// e.g. console.log('this is a debug message');
function solution(S) {
// write your code in JavaScript (Node.js 8.9.4)
// you can write to stdout for debugging purposes,
// e.g. console.log('this is a debug message');
// write your code in JavaScript (Node.js 8.9.4)
var words = S.split(" ");
var isAlpha = /^[0-9a-zA-z]*$/;
var isAlphaEven = /^[a-zA-Z]/;
var isNumeric = /^[0-9]/;
var maxLength = -1;
for(var i = 0; i <= words.length - 1; i++) {
if(words[i].match(isAlpha)
&& words[i].replace(isAlphaEven, '').length % 2 == 0
&& words[i].replace(isNumeric, '').length % 2 == 1
|| words[i].match(isNumeric)
) {
maxLength = Math.max(maxLength, words[i].length);
//console.log(words[i], maxLength);
}
}
return maxLength;
}
一個問題是模式
var isAlphaEven = /^[a-zA-Z]/;
var isNumeric = /^[0-9]/;
只能在字符串開頭匹配字符: ^
錨定到開頭。 這也不是全局匹配,因此只能替換一個字符。 另一個問題是您要用空字符串替換匹配項,而不是測試匹配項的數量。 要測試匹配數,請改用.match
和全局標志,並檢查結果數組的長度(如果沒有匹配項,則返回null):
function solution(S) { // write your code in JavaScript (Node.js 8.9.4) // you can write to stdout for debugging purposes, // eg console.log('this is a debug message'); // write your code in JavaScript (Node.js 8.9.4) var words = S.split(" "); var allAlphaNumeric = /^[\\da-z]*$/i; var alpha = /[az]/gi; var numeric = /\\d/g; var maxLength = -1; for (var i = 0; i <= words.length - 1; i++) { if (words[i].match(allAlphaNumeric) && (words[i].match(alpha) || []).length % 2 == 0 && (words[i].match(numeric) || []).length % 2 == 1 ) { maxLength = Math.max(maxLength, words[i].length); } } return maxLength; } console.log(solution("test 5 a0A pass007 ?xy1"));
請注意,您可以使用不區分大小寫的標志而不是重復a-zA-Z
,並且可以根據需要使用\\d
而不是[0-9]
。
盡管您可以使用.replace
找出匹配的數量,但是這很麻煩:您必須用空字符串替換所有不匹配的內容,這會使代碼的意圖有些混亂。
您已經有了答案,為什么您的方法無法按預期工作。
所以我想我可以通過多個.filter()
步驟添加稍微不同的方法
function findLongestWord(input) { const isAlphaNumericOnly = /^[a-z0-9]+$/i; const numbersOnly = /\\d/g; const alphaOnly = /[az]/gi; const validWords = input.split(/\\s/) .filter(word => isAlphaNumericOnly.test(word)) .filter(word => (word.match(numbersOnly) || []).length % 2 === 1) .filter(word => (word.match(alphaOnly) || []).length % 2 === 0) .sort((a, b) => b.length - a.length); return { word: validWords[0], length: validWords[0] ? validWords[0].length : -1 }; } console.log(findLongestWord("test 5 a0A pass007 ?xy1"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.