3. Longest Substring Without Repeating Characters

문제

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

주어진 문자열에서 중복되지 않는 가장 긴 문자열을 찾아 길이를 리턴하는 문제

풀이

const lengthOfLongestSubstring = (s) => {
    let max = 0;
    let temp = [];
    for ( let i = 0; i < s.length; i++ ) {
        temp = [];
        for ( let j = i; j < s.length; j++ ) {
            if ( temp.indexOf(s[j]) === -1 ) {
                temp.push(s[j]);
                if ( max < temp.length ) {
                    max = temp.length
                }
            } else {
                break;
            }
        }
    }
    return max
};

for문 한개로 짜보려 했는데 도무지 생각이 안나서 두개로 어떻게 짜긴 짰는데 별로 좋은 코드는 아닌것 같다.

그래도 쓰긴 쓴거니까 설명을 붙이자면,

temp라는 임시 배열에 j번째 원소가 없다면 푸시해주는 방식으로 해서 temp 배열 길이의 최대값을 max에 담아 리턴하는식

어렵다 난이도가 medium 밖에 안되는 문젠데 ㅜ 갈길이 멀다.

다른사람의 풀이

const lengthOfLongestSubstring = function(s) {
    let result = '';
    let tempResult = '';
    for ( let i = 0; i < s.length; i++ ) {
        if ( tempResult.indexOf(s[i]) == -1 ) {
            tempResult += s[i];
            if ( tempResult.length > result.length ) {
                result = tempResult;
            }
        } else {
            if ( tempResult.length > result.length ) {
                result = tempResult;
            }
            let index = tempResult.indexOf(s[i]);
            tempResult = tempResult.slice(index+1) + s[i];
        }
    }
    return result.length;
};

사실 코드를 보고도 어떻게 하는지 감이 딱 오진 않지만, 내가 짠 코드보다는 낫다는건 알 것 같다.

내공이 부족한것 같다.


'자료구조, 알고리즘 > leetcode 문제' 카테고리의 다른 글

9. Palindrome Number ( easy )  (0) 2017.11.01
13. Roman to Integer ( easy )  (0) 2017.10.31
7. Reverse Integer ( easy )  (0) 2017.10.30
1. Two Sum ( easy )  (0) 2017.10.29
0. LeetCode 알고리즘 풀이  (0) 2017.10.29

+ Recent posts