leetcode:1419. 数青蛙(双指针,中等)

题目:

leetcode:1419. 数青蛙(双指针,中等)_第1张图片

分析:

其实真的没想到自己能写出这么高质量的代码!
首先进行了判断:

for(int i=0;i<croakOfFrogs.size();i++)
        {
            m[croakOfFrogs[i]]++;
            if(!(m['c']>=m['r']&&m['r']>=m['o']&&m['o']>=m['a']&&m['a']>=m['k'])) return -1;
        }
        if((m['c']!=croakOfFrogs.size()/5)||(m['r']!=croakOfFrogs.size()/5)||(m['o']!=croakOfFrogs.size()/5)||
           (m['a']!=croakOfFrogs.size()/5)||(m['k']!=croakOfFrogs.size()/5)) return -1;

这一段的判断使得之后出现的一定是符合规矩的,不会出现错误的情况,很好!
然后直接双指针,找第一个c,第一个k,之间有多少个c,第二个c,第二个k,之间有多少个c即可:

for(int i=1;i<croakOfFrogs.size();i++)
        {
            if(croakOfFrogs[i]=='c') c++;
            else if(croakOfFrogs[i]=='k')
            {
                maxx=max(maxx,c);
                c--;
            }
        }

代码:

class Solution {
public:
    map<char,int> mm;
    
    int minNumberOfFrogs(string croakOfFrogs) {
        //特殊判断
        if(croakOfFrogs.size()%5!=0) return -1;
        map<char,int> m;
        for(int i=0;i<croakOfFrogs.size();i++)
        {
            m[croakOfFrogs[i]]++;
            if(!(m['c']>=m['r']&&m['r']>=m['o']&&m['o']>=m['a']&&m['a']>=m['k'])) return -1;
        }
        if((m['c']!=croakOfFrogs.size()/5)||(m['r']!=croakOfFrogs.size()/5)||(m['o']!=croakOfFrogs.size()/5)||
           (m['a']!=croakOfFrogs.size()/5)||(m['k']!=croakOfFrogs.size()/5)) return -1;
        int maxx=1;
        int c=1;
        for(int i=1;i<croakOfFrogs.size();i++)
        {
            if(croakOfFrogs[i]=='c') c++;
            else if(croakOfFrogs[i]=='k')
            {
                maxx=max(maxx,c);
                c--;
            }
        }
        return maxx;
    }
};

你可能感兴趣的:(双指针,我认为的精华)