2018年10月17日 星期三

[LeetCode] 830. position of large groups


  • Problem: position of large groups, 計算連續字母的開始與結束位置
  • Solution: 
    • 直接 iterate 整個字串
    • 第一個字母直接紀錄, 最後一組 group 要特別處理
    class Solution {
    public:
        vector> collectLargeGroups(const char *str, int len) {
            char currCh;
            int length = 0, start = 0, end = 0;
            vector> result;
            const int LARGE_SIZE = 3;
            
            if (NULL == str) return result;
            currCh = str[0];
            length = 1;
            
            for(size_t i = 1; i < len; ++i)
            {
                if (currCh != str[i])
                {
                    end = i - 1;
                    length = end - start + 1;
    
                    if (length >= LARGE_SIZE)
                    {
                        vector group{start, end};
                        result.push_back(group);
                    }
                    start = i;
                    currCh = str[i];
                }
            }
            
            // add last group
            end = len - 1;
            length = end - start + 1;
            if (length >= LARGE_SIZE)
            {
                vector group{start, end};
                result.push_back(group);
            }
            
            return result;
        }
        
        vector> largeGroupPositions(string S) {
            return collectLargeGroups(S.c_str(), S.length());
        }
    };
    

沒有留言:

張貼留言