划分字符串--尽可能多的划分片段

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表

输入:S = “ababcbacadefegdehijhklij”
输出:[9,7,8]
解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。

public List<Integer> partitionLabels2(String S) {
        int[] last = new int[26];
        int length = S.length();
        //记录每个下标最后出现的索引位置
        for (int i = 0; i < length; i++) {
            last[S.charAt(i) - 'a'] = i;
        }
        List<Integer> partition = new ArrayList<Integer>();
        int start = 0, end = 0;
        
        for (int i = 0; i < length; i++) {
            end = Math.max(end, last[S.charAt(i) - 'a']);
            //说明之前的元素都在这个这个范围内
            if (i == end) {
                partition.add(end - start + 1);
                start = end + 1;
            }
        }
        return partition;
    }
这个题目要求我们对给定的字符串 `s` 进行划分,使得每个字符仅在一个片段中出现,同时保留原字符串的顺序。我们可以使用一个简单的策略:遍历字符串,对于每个字符,将其添加到当前片段,直到遇到下一个不同的字符,然后将当前片段添加到结果列表中,并开始一个新的片段。 以下是C语言的一个解决方案: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // Function to split the string and return lengths of segments int* splitString(char *s, size_t *resultCount) { int segmentLengths[100] = {0}; // 初始化数组用于存储长度,假设最多100段 size_t currentSegmentIndex = 0; // 当前段的位置 size_t currentIndex = 0; while (currentIndex < strlen(s)) { if (currentSegmentIndex == 0 || s[currentIndex] != s[currentSegmentIndex - 1]) { segmentLengths[currentSegmentIndex++] = 1; // 遇到新字符,更新长度为1 } else { segmentLengths[currentSegmentIndex - 1]++; } currentIndex++; } *resultCount = currentSegmentIndex; // 更新结果计数器 int *lengths = malloc(*resultCount * sizeof(int)); // 分配内存存储实际长度 for (size_t i = 0; i < *resultCount; i++) { lengths[i] = segmentLengths[i]; } return lengths; } int main() { char s[] = "abccdeefgh"; size_t resultCount; int* lengths = splitString(s, &resultCount); for (size_t i = 0; i < resultCount; i++) { printf("Segment %d length: %d ", i, lengths[i]); } free(lengths); // 释放内存 return 0; } ``` 这个程序会打印出每个分割片段的长度列表,如 `"Segment 0 length: 2 Segment 1 length: 1 Segment 2 length: 1 Segment 3 length: 2"`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值