LeetCode[中等] 763. 划分字母区间
给你一个字符串 s
。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。
注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s
。
返回一个表示每个字符串片段的长度的列表。
思路 贪心算法
数组 last 存储每个字母最后出现的下标
利用滑动窗口,每次更新end指针,如果最后出现的下标 i == end,说明找到当前最大片段,则加入结果中,更新 start指针
public class Solution {public IList<int> PartitionLabels(string s) {int[] last = new int[26];for(int i = 0; i < s.Length; i++){last[s[i] - 'a'] = i;}List<int> result = new List<int>();int start = 0, end = 0;for(int i = 0; i < s.Length; i++){end = Math.Max(end, last[s[i] - 'a']);if(i == end){result.Add(end - start + 1);start = end + 1;}}return result;}
}
复杂度分析
-
时间复杂度:O(n),其中 n 是字符串 s 的长度。需要遍历字符串一次记录每个字母在字符串中最后一次出现的下标,然后需要遍历字符串一次计算划分结果。
-
空间复杂度:O(∣Σ∣),其中 Σ 是字符集,这道题中 Σ 是全部小写英语字母,∣Σ∣=26。空间复杂度主要取决于哈希表,需要使用哈希表记录每个字母在字符串中最后一次出现的下标。注意返回值不计入空间复杂度。