Skip to content

2405. Optimal Partition of String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int partitionString(string s) {
    int ans = 1;
    int used = 0;

    for (const char c : s) {
      const int i = c - 'a';
      if (used >> i & 1) {
        used = 1 << i;
        ++ans;
      } else {
        used |= 1 << i;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int partitionString(String s) {
    int ans = 1;
    int used = 0;

    for (final char c : s.toCharArray()) {
      final int i = c - 'a';
      if ((used >> i & 1) == 1) {
        used = 1 << i;
        ++ans;
      } else {
        used |= 1 << i;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def partitionString(self, s: str) -> int:
    ans = 1
    used = 0

    for c in s:
      i = string.ascii_lowercase.index(c)
      if used >> i & 1:
        used = 1 << i
        ans += 1
      else:
        used |= 1 << i

    return ans