[Algorithm] Sliding Window - findLongestSubstring

bjyyyyy·2022년 10월 5일

Sliding Window - findLongestSubstring

Write a function called findLongestSubstring, which accepts a string and returns the length of the longest substring with all distinct characters.

findLongestSubstring('') // 0
findLongestSubstring('rithmschool') // 7
findLongestSubstring('thisisawesome') // 6
findLongestSubstring('thecatinthehat') // 7
findLongestSubstring('bbbbbb') // 1
findLongestSubstring('longestsubstring') // 8
findLongestSubstring('thisishowwedoit') // 6

Time Complexity - O(n)

function findLongestSubstring(word){
  let words = {};
  let count = 0;
  let splitWord = word.split('');
  let result = []
  let start = 0;
  let end = 0;
  
  while (end < splitWord.length) {
    if (!words[splitWord[end]]) {
      words[splitWord[end]] = 1;
      end++;
      count++;
    } else {
      result.push(count)
      count = 0;
      start++;
      end = start;
      words = {};
    }
  }
  result.push(count)
  
  return Math.max(...result)
}
  1. 배열의 0번째부터 시작해서 중복되지않는 최대길이를 구한다.
  2. 중복이 발생하면 start를 1증가하고 end에 start값을 재할당, result에 count값 push, words변수 초기화를 진행한다.
  3. 해당 과정을 반복하여 end의 값이 배열의 길이보다 같거나 커지면 while 반복문 종료
  4. 남은 count 값을 result에 마저 push해주고 result 배열에서 최대값을 구한다.

0개의 댓글