Skip to content

[Leetcode] 30. Substring with Concatenation of All Words โ€‹

Problem โ€‹

๋ฌธ์ œ ๋งํฌ

์ฃผ์–ด์ง„ words ๋ฐฐ์—ด์ด ์—ฐ์†์ ์œผ๋กœ ์กด์žฌํ•˜๋Š” s ๋ฌธ์ž์—ด์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ

Solution โ€‹

  1. s ๋ฌธ์ž์—ด์„ ๋ฐ˜๋ณต๋ฌธ์„ํ†ตํ•ด ๊ฐ ์ธ๋ฑ์Šค์— ๋’ค์˜ ๋ฌธ์ž์—ด์„ ๋ฉ”์†Œ๋“œ์— ๋„˜๊น€
  2. ๋„˜๊ธด ๋ฌธ์ž์—ด์—์„œ ์ฒซ๋ฒˆ์งธ ์ธ๋ฑ์Šค์˜ ๋ฌธ์ž๊ฐ€ (๊ธธ์ด๊ฐ€ ๊ฐ™์€๊ฒƒ์„์ด์šฉ) ๋ฐฐ์—ด์— ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ
  3. ์กด์žฌํ•œ๋‹ค๋ฉด ๋ฌธ์ž์—ด์—์„œ ํ•ด๋‹น ๊ฐ’์„ ์ œ๊ฑฐํ•˜๊ณ  ๋ฐฐ์—ด์—์„œ๊ณ  ์ œ๊ฑฐ ํ›„ ๋ฉ”์†Œ๋“œ๋กœ ๋‹ค์‹œ๋„˜๊น€(์žฌ๊ท€ํ•จ์ˆ˜ ์‚ฌ์šฉ)
  4. ๋ฐฐ์—ด์˜ ๊ฐ’์ด ๋น„์–ด์žˆ๋‹ค๋ฉด ๋ชจ๋“  ๊ฐ’์ด ๊ฒ€์‚ฌ๊ฐ€๋œ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅ

JS Code โ€‹

js
/**
 * @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
}