C++ | 100% Speed with explanation
class Solution {
public:
    vector<int> partitionLabels(string S) {       
        vector<int> answer;
        
        // Char and their last index
        unordered_map<char, int> hashy;
        
        // Add every char and their last index to the hashmap.
        // We know this is their last index because it overwrites everytime
        for(int i = 0; i < S.size(); i++){
            hashy[S[i]] = i;
        }
        
        int first = 0;
        int last = 0;
        
        // Iterate through until you get the last member of all things before the end
        for(int i = 0; i < S.size(); i++){
            // The last becomes the char in the partition with the greatest last index
            unordered_map<char,int>::iterator it = hashy.find(S[i]);
            last = max(last, it->second);   
            
            // If we get to the last index of the partition, add the length of the partition and reset. 
            if(i == last){
                answer.push_back(last - first + 1);
                last = 0;
                first = i + 1;
            }
        }
        return answer;
    }
};
Comments (0)