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 theminimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Input: s ="abacaba"Output: 4Explanation:
Two possible partitions are("a","ba","cab","a") and ("ab","a","ca","ba").It can be shown that 4is the minimum number of substrings needed.
To minimize the number of substrings with unique characters, we greedily extend the current substring until we see a repeated character, then start a new substring. This ensures each substring is as long as possible without duplicates.
classSolution {
public:int partitionString(string s) {
unordered_set<char> st;
int ans =0;
for (char c : s) {
if (st.count(c)) {
ans++;
st.clear();
}
st.insert(c);
}
return ans +1;
}
};
classSolution {
publicintpartitionString(String s) {
Set<Character> st =new HashSet<>();
int ans = 0;
for (char c : s.toCharArray()) {
if (st.contains(c)) {
ans++;
st.clear();
}
st.add(c);
}
return ans + 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funpartitionString(s: String): Int {
val st = mutableSetOf<Char>()
var ans = 0for (c in s) {
if (c in st) {
ans++ st.clear()
}
st.add(c)
}
return ans + 1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defpartitionString(self, s: str) -> int:
st: set[str] = set()
ans =0for c in s:
if c in st:
ans +=1 st.clear()
st.add(c)
return ans +1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnpartition_string(s: String) -> i32 {
letmut st = std::collections::HashSet::new();
letmut ans =0;
for c in s.chars() {
if st.contains(&c) {
ans +=1;
st.clear();
}
st.insert(c);
}
ans +1 }
}