๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 763 - Partition Labels (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 763๋ฒˆ

ํ’€์ด ๊ณผ์ •

ํˆฌ ํฌ์ธํ„ฐ ์™€ ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

partition ์ด ํŠน์ • ๋ฌธ์ž๋“ค์˜ ์ง‘ํ•ฉ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์„ ๋•Œ
๊ฐ€์žฅ ๋งŽ์€ partition ์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ ์œ„ํ•ด์„œ๋Š” ์šฐ์„  ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋จผ์ € partition A ์˜ ๊ฐ€์žฅ ์ฒซ ๋ฌธ์ž๊ฐ€ a ๋ผ๊ณ  ํ•œ๋‹ค๋ฉด,
ํ•ด๋‹น partition ์—๋Š” ๋ฌธ์ž์—ด S ์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  a ๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋ฌธ์ž์—ด S ์—์„œ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ์กด์žฌํ•˜๋Š” a ๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.
๊ทธ๋Ÿฌ๋ฏ€๋กœ partition ์˜ ๊ธฐ์ค€์ด ๋˜๋Š” ํฌ์ธํ„ฐ right ์™€
๊ฐ partition ์˜ ๋ฌธ์ž๋“ค์„ ๊ฒ€์‚ฌํ•˜๊ธฐ ์œ„ํ•œ ํฌ์ธํ„ฐ left ๋ฅผ ์„ ์–ธํ•ด์„œ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {string} S
 * @return {number[]}
 */
var partitionLabels = function (S) {
  const answer = [];
  let left = 0;

  while (left < S.length) {
    let start = left;
    let right = S.lastIndexOf(S[left]);

    while (left < right) {
      right = Math.max(right, S.lastIndexOf(S[left++]));
    }
    left++;
    answer.push(right - start + 1);
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 752 - Open the Lock (Medium)  (0) 2021.03.04
LeetCode 11 - Container With Most Water (Medium)  (0) 2021.03.04
LeetCode 48 - Rotate Image (Medium)  (0) 2021.03.04
LeetCode 236 - Lowest Common Ancestor of a Binary Tree (Medium)  (0) 2021.03.04
LeetCode 494 - Target Sum (Medium)  (0) 2021.03.04

๐Ÿ’ฌ ๋Œ“๊ธ€