我在这里遇到以下问题:我需要找出唯一字符的最长子串的长度。
就像,我有一个字符串thequickbrownfoxjumpsoveralazydog
,我希望得到14
(长度为thequickbrownf
)
我在这里发现了许多与此主题相关的主题,但是我似乎无法将这些解决方案(如果有)翻译成Javascript。
伙计们,您愿意帮我吗?预先感谢一百万!
答案 0 :(得分:1)
一种选择是使用Set
,当您发现重复的字符并在O(N)
时间运行时将其重置:
const str = 'thequickbrownfoxjumpsoveralazydog';
let set = new Set();
let bestRecordSoFar = 0;
let currRecord = 0;
[...str].forEach((char) => {
if (set.has(char)) {
bestRecordSoFar = Math.max(bestRecordSoFar, currRecord);
set = new Set();
currRecord = 0;
}
set.add(char);
currRecord++;
});
const best = Math.max(bestRecordSoFar, currRecord);
console.log(best);
答案 1 :(得分:0)
现有答案无法正常运行,因为它们仅搜索从特定位置(字符串的开头以及紧接在某些重复字符之后)开始的最长的唯一子字符串。它们碰巧为'thequickbrownfoxjumpsoveralazydog'
提供了正确的答案,因为最长的唯一子字符串在字符串的开头。它们不适用于'zabzcd'
这样的字符串,最长的字符串从第二个位置开始,长度为5。
这将适用于所有情况:
const tests = [
'thequickbrownfoxjumpsoveralazydog', // 14
'zabzcd', // 5
'zabzcdthequickbrownfox', // 15
];
console.log( tests.map( get_max_unique_substring_length ) );
function get_max_unique_substring_length ( str ) {
let unique_str = '';
let max_length = 0;
for ( let i = 0; i < str.length; i++ ) {
const char = str[i];
const char_pos = unique_str.indexOf( char );
if ( char_pos >= 0 )
unique_str = unique_str.substr( char_pos + 1);
unique_str += char;
max_length = Math.max( unique_str.length, max_length );
}
return max_length;
}
答案 2 :(得分:-1)
(根据您的评论)考虑到您并没有真正找到想要找到的算法,我为代码提供了逐步说明。
主要概念是遍历字符串,每次找到重复的字符串时将一个字符向右移,并比较那些唯一字符子字符串的长度以找到最长的子字符串:
//input string
const src = 'thequickbrownfoxjumpsoveralazydog';
//iterate over the string characters and reduce that
//to object where property 'start' stores the beginning
//of the last non-repetitive substring and the property
//'len' would hold the length of the longest such subsstring
const longestUniqueSub = str => [...str].reduce((res, char, index, src) => {
//find duplicating characters starting from the beginning of the current
//unique-character substring up until the current character index
const dupIndex = src.slice(0,index).indexOf(char, res.start + 1);
//if match is found
if (dupIndex > -1) {
//get the length of the current unique substring
const len = index - res.start - 1;
//if that substring appears to be the longest, store that
if(res.len < len) res.len = len;
//start new unique-character substring
res.start = dupIndex + 1;
}
return res;
}, {start: -1, len: 1}).len;
console.log(longestUniqueSub(src));