Published:
Updated:


Solution

package leetcode.sully.week2;

import java.util.ArrayList;
import java.util.List;

public class PartitionLabels {
    // ababcbaca defegde hijhklij -> [9, 7, 8]
    public List<Integer> partitionLabels(String s) {
        List<Integer> answer = new ArrayList<>();
        int lastIndex = 0;
        int start = 0;

        // i == 0: lastIndexOf๋กœ ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž์™€ ๊ฐ™์„ ๋•Œ๋ฅผ ์ฐพ๊ณ  ๊ตฌ์—ญ ๋‚˜๋ˆˆ๋‹ค -> index ๊ฐ’ ์ €์žฅ
        // i == 1: ๊ทธ index ๊ฐ’์„ i == 0์ผ ๋•Œ์™€ ๋น„๊ตํ•˜์—ฌ index < i๋ผ๋ฉด ๊ตฌ์—ญ์„ ์œ„์˜ ๋กœ์ง์œผ๋กœ ๋‹ค์‹œ ๋‚˜๋ˆ„๊ธฐ

        for (int i = 0; i < s.length(); i++) {
            start ++;
            // ๊ณ„์† for๋ฌธ ๋Œ๋‹ค๊ฐ€ lastIndex ์œ„์น˜๊ฐ€ ๋” ํฐ ๊ฑธ๋กœ ์ €์žฅ
            if (s.lastIndexOf(s.charAt(i)) > lastIndex) {
                lastIndex = s.lastIndexOf(s.charAt(i));
            }

            // ์˜ค ์ด์ œ ์—ฌ๊ธฐ์„œ ํŒŒํ‹ฐ์…˜ ๋ถ„๋ฆฌ ํ•ด์ฃผ๋ฉด ๋˜๊ฒ ์ง€?
            if (lastIndex == i) { // lastIndex์— i๊ฐ€ ๋„๋‹ฌ์„ ํ•˜๋ฉด ์ด์ œ ์ž˜๋ผ์ค˜์•ผ๊ฒ ์ง€ -> ๊ทผ๋ฐ ์–ด๋–ป๊ฒŒ ์ž๋ฅผ๊นŒ
                answer.add(start); // i๋ฒˆ์งธ๋ฅผ ๋„ฃ์–ด์ฃผ๊ณ 
                start = 0; // ๋‹ค์‹œ ์ดˆ๊ธฐํ™”
            }
        }

        return answer;
    }
}

Leave a comment