[Leetcode] 30. Substring with Concatenation of All Words

Seongjun Lee·2022년 2월 19일
0

[Leetcode] - Problem

목록 보기
30/43
post-thumbnail

Problem

문제 링크

주어진 words 배열이 연속적으로 존재하는 s 문자열의 인덱스를 구하는 문제

Solution

  1. s 문자열을 반복문을통해 각 인덱스에 뒤의 문자열을 메소드에 넘김
  2. 넘긴 문자열에서 첫번째 인덱스의 문자가 (길이가 같은것을이용) 배열에 존재하는지 확인
  3. 존재한다면 문자열에서 해당 값을 제거하고 배열에서고 제거 후 메소드로 다시넘김(재귀함수 사용)
  4. 배열의 값이 비어있다면 모든 값이 검사가된것이기 때문에 해당 인덱스를 저장

JS Code

/**
 * @param {string} s
 * @param {string[]} words
 * @return {number[]}
 */
var findSubstring = function (s, words) {
  let answer = []
  const size = words[0].length
  const totalSize = words.reduce((total, cur) => total + cur.length, 0)

  const play = (str, words) => {
    if (!words.length) return true

    const word = str.substring(0, size)
    const wordIdx = words.indexOf(word)
    if (!!~wordIdx) {
      words.splice(wordIdx, 1)
      return play(str.substring(size), words)
    }
    return false
  }

  for (let i = 0; i <= s.length - totalSize; i++) {
    if (play(s.substring(i), [...words])) answer.push(i)
  }

  return answer
}
profile
Hi there 👋

0개의 댓글