comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
Medium |
1355 |
Weekly Contest 310 Q2 |
|
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 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").
Constraints:
1 <= s.length <= 105
s
consists of only English lowercase letters.
According to the problem description, each substring should be as long as possible and contain unique characters. Therefore, we can greedily partition the string.
We define a binary integer
Traverse each character in the string
Finally, return
The time complexity is
class Solution:
def partitionString(self, s: str) -> int:
ans, mask = 1, 0
for x in map(lambda c: ord(c) - ord("a"), s):
if mask >> x & 1:
ans += 1
mask = 0
mask |= 1 << x
return ans
class Solution {
public int partitionString(String s) {
int ans = 1, mask = 0;
for (int i = 0; i < s.length(); ++i) {
int x = s.charAt(i) - 'a';
if ((mask >> x & 1) == 1) {
++ans;
mask = 0;
}
mask |= 1 << x;
}
return ans;
}
}
class Solution {
public:
int partitionString(string s) {
int ans = 1, mask = 0;
for (char& c : s) {
int x = c - 'a';
if (mask >> x & 1) {
++ans;
mask = 0;
}
mask |= 1 << x;
}
return ans;
}
};
func partitionString(s string) int {
ans, mask := 1, 0
for _, c := range s {
x := int(c - 'a')
if mask>>x&1 == 1 {
ans++
mask = 0
}
mask |= 1 << x
}
return ans
}
function partitionString(s: string): number {
let [ans, mask] = [1, 0];
for (const c of s) {
const x = c.charCodeAt(0) - 97;
if ((mask >> x) & 1) {
++ans;
mask = 0;
}
mask |= 1 << x;
}
return ans;
}
impl Solution {
pub fn partition_string(s: String) -> i32 {
let mut ans = 1;
let mut mask = 0;
for x in s.chars().map(|c| (c as u8 - b'a') as u32) {
if mask >> x & 1 == 1 {
ans += 1;
mask = 0;
}
mask |= 1 << x;
}
ans
}
}