https://leetcode.com/problems/partition-labels/
Partition Labels - LeetCode
Can you solve this real interview question? Partition Labels - You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc" can be partitioned int
leetcode.com
같은 문자들은 한 구간으로 묶어 해당 구간들의 크기를 리턴하는 문제이다. 아이디어가 떠올라 쉬운 편인 문제였다. 현재 구간의 가장 마지막 끝은 구간 내의 모든 문자들을 포함 해야 하므로, 가장 큰 lastIndex의 값을 체크하면서 갱신하면 구간을 찾을 수 있다.
자바의 경우 String 클래스의 lastIndexOf 메서드를 통해 마지막 인덱스를 쉽게 찾을 수 있으므로 해당 메서드를 활용해서 문제를 해결해 주었다.
import java.util.*;
public class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> answer = new ArrayList<>();
for(int i = 0; i < s.length(); i++){
int lastIdx = s.lastIndexOf(s.charAt(i));
int now = i;
while(now++ < lastIdx){
lastIdx = Math.max(lastIdx, s.lastIndexOf(s.charAt(now)));
}
answer.add(lastIdx - i + 1);
i = now - 1;
}
return answer;
}
}
'Algolithm-Leetcode > Greedy' 카테고리의 다른 글
| Gas Station (0) | 2026.08.18 |
|---|---|
| Jump Game 2 (0) | 2026.08.13 |
| Can Jump (0) | 2026.08.06 |