| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | 
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | 
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | 
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | 
| 30 | 
- 재귀함수
 - 우선순위 큐
 - HashMap
 - programmers
 - 깊이우선탐색
 - ArrayList
 - priority queue
 - DP
 - Java
 - string
 - 리트코드
 - 브루트포스
 - recursion
 - hashset
 - binary tree
 - two pointers
 - coding
 - 알고리즘
 - 부분배열
 - PCCP
 - dfs
 - Algorithm
 - leetcode
 - Array
 - greedy
 
- Today
 
- Total
 
지식창고
[Java] LeetCode 2405. Optimal Partition of String 본문
[Java] LeetCode 2405. Optimal Partition of String
문 제 :
String s 가 주어진다. s를 substring으로 나눈다.
나누는 조건은 다음과 같다.
- substring 안에서의 각 character들은 유니크 하다.
위와 같은 조건으로 s를 substring으로 나누었을 때, substring의 최소 개수를 구하여라.
Constraint
{ 1 <= s.length <= 10^5 }
{ s is only lowercase }
Matter
Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example )
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
=========================================================================
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
접   근 : 
HashSet을 이용한 Greedy적 접근
해 결 & 설 명:
substring의 개수를 저장하는 변수 : res
반복문을 돌면서 String s의 character를 하나 씩 확인한다.
HashSet을 선언하고 반환값이 true이면 계속 추가해나간다. (똑같은 글자가 추가되지 않을때까지)
만약 똑같은 글자가 나왔거나, 반복문의 범위가 s.length를 벗어났다면
HashSet에 추가하는 과정(substring을 늘리는 과정)을 멈춘다.
그리고 res++해준다.
결 과 :
class Solution {
    public int partitionString(String s) {
        int res=0;
        for(int i=0; i<s.length(); i++){
            Set<Character> set = new HashSet<>();
            set.add(s.charAt(i));
            
            while(i<s.length()-1 && set.add(s.charAt(i+1)) == true){
                i++;
            }
            res++;
        }
        return res;
    }
    
}'Algorithm > Leetcode' 카테고리의 다른 글
| [Java] LeetCode 347. Top K Frequent Elements (0) | 2023.05.23 | 
|---|---|
| [Java] LeetCode 1721. Swapping Nodes in a Linked List (0) | 2023.05.15 | 
| [Java] LeetCode 1402. Reducing Dishes (0) | 2023.03.29 | 
| [Java] LeetCode 2316. Count Unreachable Pairs of Nodes in an Undirected Graph (0) | 2023.03.25 | 
| [Java] LeetCode 1319. Number of Operations to Make Network Connected (0) | 2023.03.23 |