问题
按字母顺序查找最长的子字符串。
示例:“asdfaaaabbbbcttavvfffffdf”中最长的字母子串是“aaaabbbbctt”。
有些测试的字符串长度可达 10,000 个字符,因此您的代码需要高效。
输入内容仅包含小写字符,且长度至少为一个字母。
如果有多个解决方案,请返回第一个出现的解决方案。
我的解决方案
function longest(str) {
//first element of count == total count of the highest number
//second element of count == longest str so far
let count = [0, ''];
//temp count == length of current str
let tempCount = [0];
//split the str to an array
let strArr = str.split('');
//loop through each letter of the string
for(let i = 0; i < strArr.length; i++){
//if the character is higher in the alpahabet than the last then
if(convertToNumber(strArr[i])<convertToNumber((strArr[i]-1)) || convertToNumber((strArr[i]-1))== undefined){
tempCount[0]++;
//if the current character is not higher than the last
} else {
if(tempCount[0] > count[0]){
//change the longest str number to the length of this str
count[0] = tempCount[0];
//slice the new longest str
let longestStr = strArr.slice(strArr[i]-tempCount[0], strArr[i]);
//join the str together
count[1] = longestStr.join('');
//reset the temp count
tempCount[0] = 0;
} else {
//reset the temp count
tempCount[0] = 0;
}
}
}
//converts the relevant letter to a code
function convertToNumber(letter){
return letter.charCodeAt(0);
}
//returns the longest str
return count[1];
}
console.log(longest('asdfaaaabbbbcttavvfffffdf'));
算法返回“letter.charCodeAt 不是函数”
为什么会出现这种情况?我该如何调整来修复算法?
最佳答案
问题出在这里:
if(convertToNumber(strArr[i])<convertToNumber((strArr[i]-1)) || convertToNumber((strArr[i]-1))== undefined)
您正在尝试从字母(字符串)中减去 1(数字)。它应该是strArr[i-1]
。
而且 即使修复后,您仍然会收到以下错误:
convertToNumber(strArr[i]) < convertToNumber(strArr[i-1])
如果i
为零,因为strArr[-1]
将给出未定义。
const arr = [1, 2, 3];
console.log(arr[-1]);
基本上是undefined.charCodeAt(0);
,这会产生错误。
关于javascript - 为什么这个嵌入函数不起作用(在 javascript 算法内部),从而阻止 javascript 算法被解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63316516/