https://leetcode.com/problems/partition-labels/description/
A string S
of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:
S
will have length in range[1, 500]
.S
will consist of lowercase letters ('a'
to'z'
) only.
- 字符串中等题。滑动窗口+贪心。时间复杂度O(N),空间复杂度O(N)。
- 首先依然是做hash,不过这次是对所有char记录它们最后出现的位置。
- 然后定义三个指针,window开始left和结束right,当前i。每次移动i,然后判断当前S[i]最后出现的位置是否大于当前right,如果是,则扩展right为last[S[i]]。
- 如果当前i == window结束right,则代表当前window中所有的字符都只在当前window中出现。所以可以把当前window的size记录。同时移动left到下一个window的起点。
- https://leetcode.com/problems/partition-labels/solution/
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <vector> 11 #include <unordered_map> 12 using namespace std; 13 14 class Solution { 15 public: 16 vector<int> partitionLabels(string S) { 17 vector<int> vResult; 18 19 // corner case 20 if (S.empty()) return vResult; 21 22 unordered_map<char, int> last; 23 24 // the last occurred index of S[i] 25 for (int i = 0; i < S.size(); ++ i) 26 last[S.at(i)] = i; 27 28 // start and end of the current window 29 int left = 0, right = 0; 30 31 // current pointer 32 for (int i = 0; i < S.size(); ++ i) { 33 right = max(right, last[S.at(i)]); // maximum index of the current window 34 35 // reach the end of current window 36 if (i == right) { 37 vResult.push_back(right - left + 1); // size of the current window 38 left = i + 1; // move to start of the next window 39 } 40 } 41 42 return vResult; 43 } 44 }; 45 46 int main(int argc, char* argv[]) 47 { 48 Solution testSolution; 49 50 vector<string> inputs = {"", "ababcbacadefegdehijhklij", "abcdefg", "aaaaaaaaaa"}; 51 vector<int> result; 52 53 /* 54 55 9 7 8 56 1 1 1 1 1 1 1 57 10 58 */ 59 for (auto input : inputs) { 60 result = testSolution.partitionLabels(input); 61 62 for (auto it : result) 63 cout << it << " "; 64 cout << endl; 65 } 66 67 return 0; 68 }