LeetCode 코딩 문제 2020/12/15 - Longest Substring Without Repeating Characters

이호현·2020년 12월 15일
1

Algorithm

목록 보기
35/138

[문제]

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

(요약) 문자열에서 알파벳이 중복으로 안들어가 있게 자를 때 가장 긴 문자열의 길이를 return하라.

[풀이]

var lengthOfLongestSubstring = function(s) {
  const strArr = [];
  let tempStr = '';
   
  for(let i = 0; i < s.length; i++) {
    if(!tempStr.includes(s[i])) {
      tempStr += s[i];
    }
    else {
      const index = tempStr.indexOf(s[i]);
      strArr.push(tempStr);
      tempStr = tempStr.slice(index + 1) + s[i];
    }
  }
  strArr.push(tempStr);
  
  return Math.max(...strArr.map(str => str.length));
};

문자열 처음부터 순회하면서 같은 알파벳이 나오지 않으면 tempStr에 계속 추가하고, 같은 알파벳이 나오면 그 전까지 tempStrstrArrpush함.
그리고 tempSre에 있는 중복된 알파벳 다음 문자부터 다시 tempStr에 추가 반복.

profile
평생 개발자로 살고싶습니다

0개의 댓글