# 【LeetCode】 2405. Optimal Partition of String ## Description > 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. > Constraints: `1 <= s.length <= 105` `s` consists of only English lowercase letters. > 給一字串 `s`,將該字串切割為一段或是多段的子字串,且每段子字串中的字母都得是唯一的。也就是說,任意一個子字串中,不會有字母出現超過一次。 > 回傳分割後子字串數量的**最小值**。 > 注意,在一個合理的分割後每個字元都應該剛好屬於一個子字串 > 限制: `1 <= s.length <= 105` `s` 只會包含小寫的英文字母 ## Example: ``` Example 1: 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. ``` ``` Example 2: Input: s = "ssssss" Output: 6 Explanation: The only valid partition is ("s","s","s","s","s","s"). ``` ## Solution * 用貪婪演算法就可以解了 * 從字串頭開始往後面遍歷,檢查該字元是否出現在子字串中 * 如果沒有,將該字元加入子字串 * 如果有,將子字串清空,答案數量加一(開始下一個子字串的概念) * 實作上為了加速,子字串的部分可用 hash map,加速搜尋字元是否出現過的部分 ### Code ```C++=1 class Solution { public: int partitionString(string s) { set<char> unique_char; int count = 0; for(int i = 0; i < s.length(); i++) { if(unique_char.count(s[i]) != 0) { count++; unique_char.clear(); } unique_char.insert(s[i]); } return count + 1; } }; ``` ###### tags: `LeetCode` `C++`