classSolution { public: vector<int> partitionLabels(string s){ int last[26]; int length = s.size(); for (int i = 0; i < length; i++) { last[s[i] - 'a'] = i; } vector<int> partition; int start = 0, end = 0; for (int i = 0; i < length; i++) { end = max(end, last[s[i] - 'a']); if (i == end) { partition.push_back(end - start + 1); start = end + 1; } } return partition; } };
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var partitionLabels = function(s) { const last = newArray(26); const length = s.length; const codePointA = 'a'.codePointAt(0); for (let i = 0; i < length; i++) { last[s.codePointAt(i) - codePointA] = i; } const partition = []; let start = 0, end = 0; for (let i = 0; i < length; i++) { end = Math.max(end, last[s.codePointAt(i) - codePointA]); if (i == end) { partition.push(end - start + 1); start = end + 1; } } return partition; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defpartitionLabels(self, s: str) -> List[int]: last = [0] * 26 for i, ch inenumerate(s): last[ord(ch) - ord("a")] = i partition = list() start = end = 0 for i, ch inenumerate(s): end = max(end, last[ord(ch) - ord("a")]) if i == end: partition.append(end - start + 1) start = end + 1 return partition
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcpartitionLabels(s string) (partition []int) { lastPos := [26]int{} for i, c := range s { lastPos[c-'a'] = i } start, end := 0, 0 for i, c := range s { if lastPos[c-'a'] > end { end = lastPos[c-'a'] } if i == end { partition = append(partition, end-start+1) start = end + 1 } } return }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int* partitionLabels(char* s, int* returnSize) { int last[26]; int length = strlen(s); for (int i = 0; i < length; i++) { last[s[i] - 'a'] = i; } int* partition = malloc(sizeof(int) * length); int start = 0, end = 0; *returnSize = 0; for (int i = 0; i < length; i++) { end = fmax(end, last[s[i] - 'a']); if (i == end) { partition[(*returnSize)++] = end - start + 1; start = end + 1; } } return partition; }
复杂度分析
时间复杂度:O(n),其中 n 是字符串的长度。需要遍历字符串两次,第一次遍历时记录每个字母最后一次出现的下标位置,第二次遍历时进行字符串的划分。