LeetCode - 3.Longest Substring Without Repeating Characters


コード#コード#

var lengthOfLongestSubstring = function(s) {
    
    const arr = s.split('');
    let longestWord = '';
    let newWord = '';
    let answer = 0;
    arr.map((a) => {
        const idx = newWord.indexOf(a);
        if(idx !== -1) {
            if(answer < newWord.length) {
                longestWord = newWord;
                answer = newWord.length;
            }
            newWord = newWord.slice(idx+1) + a;
            
        } else {
            newWord += a;
        }
    })
    if(answer < newWord.length) {
                longestWord = newWord;
                answer = newWord.length;
    }
    
    return answer;
};

解答と感想


最近忙しくて、コードテストの問題をあまりできなかったので、なぜかできました.コードがはっきりしていないが、これはO(n)で解決された問題である.字ごとに存在するか否かを判断し、字があればその字から接続し、問題を解決した.