[leetcode] 1525. Number of Good Ways to Split a String
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
You are given a string s, a split is called good if you can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are 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").
Example 3:
Input: s = "aaaaa"
Output: 4
Explanation: All possible splits are good.
Example 4:
Input: s = "acbadbaada"
Output: 2
Constraints:
- s contains only lowercase English letters.
- 1 <= s.length <= 10^5
分析
题目的意思是:给定一个字符还,然后切分成两个非空字符串,是的两字符串所包含字符的类别数相等。思想也很直接,用字典d统计字符串s字符的频率,然后用s1记录遍历的时候以该位置为分割点左边字符串的字符的种类数,根据d求出以该位置为分割点右边字符串的字符种类数,这样判断一下长度是否相等就能得出结果了。
代码
class Solution:
def numSplits(self, s: str) -> int:
d=collections.defaultdict(int)
for ch in s:
d[ch]+=1
s1=set()
res=0
for ch in s:
s1.add(ch)
d[ch]-=1
if(d[ch]==0):
del d[ch]
if(len(s1)==len(d)):
res+=1
return res
参考文献
[LeetCode] Very simple python 🐍 solution using counter Dict with comments