首页 > 试题广场 >

字符串分割

[编程题]字符串分割
  • 热度指数:1910 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个由小写字母组成的字符串s,请将其分割成尽量多的子串,并保证每个字母最多只在其中一个子串中出现。请返回由一个或多个整数表示的分割后各子串的长度。


输入描述:
来自标准输入的一行由小写字母组成的字符串。


输出描述:
字符串最优分割后各子串的长度,多个数字之间由空格分隔。
示例1

输入

ababbacadefgdehijhklij

输出

8 6 8

说明

该样例下最优的分割为"ababbaca" + "defgde" + "hijhklij",在该分割下字母abc仅出现在"ababbaca"中、字母defg仅出现在"defgde"中、字母hijkl仅出现在"hijhklij"中
要求将其“分割为尽量多的子串”意味着像"ababbacadefgde" + "hijhklij"这样的分割也是合法的,但在本题中并不是最优解
""""
找到字母的左右边界,合并有交集的区间
"""

if __name__ == "__main__":
    s = input().strip()
    a = [[-1] * 2 for _ in range(26)]
    for i in range(len(s)):
        if a[ord(s[i]) - ord('a')][0] == -1:
            a[ord(s[i]) - ord('a')][0] = i
        a[ord(s[i]) - ord('a')][1] = i
    a.sort(key=(lambda x: x[0]))
    t, p_max, p_min = 0, 0, 0
    ans = []
    for t in range(0, 26):
        if a[t][0] == -1: continue
        if a[t][0] > p_max:
            ans.append(p_max - p_min + 1)
            p_min = a[t][0]
        p_max = max(p_max, a[t][1])
    ans.append(p_max - p_min + 1)
    print(' '.join(map(str, ans)))

发表于 2019-07-16 13:02:49 回复(0)