返回介绍

solution / 1500-1599 / 1525.Number of Good Ways to Split a String / README_EN

发布于 2024-06-17 01:03:18 字数 3937 浏览 0 评论 0 收藏 0

1525. Number of Good Ways to Split a String

中文文档

Description

You are given a string s.

A split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.

Return _the number of good splits you can make in s_.

 

Example 1:

Input: s = "aacaba"
Output: 2
Explanation: There are 5 ways to split "aacaba" and 2 of them are good. 
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.

Example 2:

Input: s = "abcd"
Output: 1
Explanation: Split the string as follows ("ab", "cd").

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Solutions

Solution 1

class Solution:
  def numSplits(self, s: str) -> int:
    cnt = Counter(s)
    vis = set()
    ans = 0
    for c in s:
      vis.add(c)
      cnt[c] -= 1
      if cnt[c] == 0:
        cnt.pop(c)
      ans += len(vis) == len(cnt)
    return ans
class Solution {
  public int numSplits(String s) {
    Map<Character, Integer> cnt = new HashMap<>();
    for (char c : s.toCharArray()) {
      cnt.merge(c, 1, Integer::sum);
    }
    Set<Character> vis = new HashSet<>();
    int ans = 0;
    for (char c : s.toCharArray()) {
      vis.add(c);
      if (cnt.merge(c, -1, Integer::sum) == 0) {
        cnt.remove(c);
      }
      if (vis.size() == cnt.size()) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int numSplits(string s) {
    unordered_map<char, int> cnt;
    for (char& c : s) {
      ++cnt[c];
    }
    unordered_set<char> vis;
    int ans = 0;
    for (char& c : s) {
      vis.insert(c);
      if (--cnt[c] == 0) {
        cnt.erase(c);
      }
      ans += vis.size() == cnt.size();
    }
    return ans;
  }
};
func numSplits(s string) (ans int) {
  cnt := map[rune]int{}
  for _, c := range s {
    cnt[c]++
  }
  vis := map[rune]bool{}
  for _, c := range s {
    vis[c] = true
    cnt[c]--
    if cnt[c] == 0 {
      delete(cnt, c)
    }
    if len(vis) == len(cnt) {
      ans++
    }
  }
  return
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文