leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 9aaab2ea9c483997ba3a9c1235cd38125fa68d69
parent 9e00d6582e7b3758610b8dab014180dc15171c00
Author: Jack Sangdahl <jack@pngu.org>
Date:   Thu,  1 Jan 2026 20:00:45 -0700

1525. number of good ways to split a string

Diffstat:
Anum_good_ways_split_str.c | 33+++++++++++++++++++++++++++++++++
Anum_good_ways_split_str.py | 33+++++++++++++++++++++++++++++++++
2 files changed, 66 insertions(+), 0 deletions(-)

diff --git a/num_good_ways_split_str.c b/num_good_ways_split_str.c @@ -0,0 +1,33 @@ +// 1525. Number of Good Ways to Split a String +#include "leetcode.h" + +/* + * you are given a string 's'. a split is called good if you can split 's' into + * two non-empty strings 's_left' and 's_right' where their concatenation is + * equal to 's' (ie. 's_left + s_right = s') and the number of distinct letters + * in 's_left' and 's_right' is the same. return the number of good splits you + * can make in 's'. + */ + +int numSplits(char *s) { + int l_map[26] = {0}, r_map[26] = {0}; + int cnt = 0, l_char = 0, r_char = 0, n = strlen(s); + for (int i = 0; i < n; i++) + if (!r_map[s[i] - 'a']++) + r_char++; + for (int i = 0; i < n - 1; i++) { + if (!l_map[s[i] - 'a']++) + l_char++; + if (!--r_map[s[i] - 'a']) + r_char--; + if (l_char == r_char) + cnt++; + } + return cnt; +} + +int main() { + char *s1 = "aacaba", *s2 = "abcd"; + printf("%d\n", numSplits(s1)); // expect: 2 + printf("%d\n", numSplits(s2)); // expect: 1 +} diff --git a/num_good_ways_split_str.py b/num_good_ways_split_str.py @@ -0,0 +1,33 @@ +# 1525. Number of Good Ways to Split a String +from collections import Counter + +""" +you are given a string 's'. a split is called good if you can split 's' into +two non-empty strings 's_left' and 's_right' where their concatenation is +equal to 's' (ie. 's_left + s_right = s') and the number of distinct letters +in 's_left' and 's_right' is the same. return the number of good splits you +can make in 's'. +""" + + +class Solution(object): + def numSplits(self, s): + """ + :type s: str + :rtype: int + """ + l_map, r_map, cnt = Counter(), Counter(), 0 + for i in s: + l_map[i] += 1 + r_map[i] -= 1 + if r_map[i] == 0: + del r_map[i] + if len(l_map) == len(r_map): + cnt += 1 + return cnt + + +if __name__ == "__main__": + obj = Solution() + print(obj.numSplits(s="aacaba")) + print(obj.numSplits(s="abcd"))