• 【leetcode】1525. Number of Good Ways to Split a String


    题目如下:

    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

    解题思路:本题不难,首先统计出s中所有字符出现的次数,然后再从左往右遍历s,依次减少之前统计的结果即可。

    代码如下:

    class Solution(object):
        def numSplits(self, s):
            """
            :type s: str
            :rtype: int
            """
            res = 0
            dic_right = {}
            dic_left = {}
            for i in s:
                dic_right[i] = dic_right.setdefault(i,0) + 1
            for i in s:
                dic_left[i] = dic_left.setdefault(i,0)+1
                dic_right[i] -= 1
                if dic_right[i] == 0:
                    del dic_right[i]
                if len(dic_left) == len(dic_right):
                    res += 1
    
            return res
  • 相关阅读:
    现代软件工程 第八章 【需求分析】练习与讨论
    现代软件工程 第七章 【MSF】练习与讨论
    现代软件工程 第六章 【敏捷流程】练习与讨论
    PPT演说技巧
    Mac上最强大的截图软件-xnip
    什么是函数倾轧(name mangling)?
    编程--在线提交系统(Online Judge)
    C++ 的多继承与虚继承
    C++ 中 string和char* 的区别
    编程语言中优先级与结合性
  • 原文地址:https://www.cnblogs.com/seyjs/p/13666898.html
Copyright © 2020-2023  润新知