题目讲解
1419. 数青蛙
算法讲解
cpp
复制代码
class Solution {
public:
int minNumberOfFrogs(string croakOfFrogs) {
string target = "croak";
int n = target.size();
//保存target每个字符的位置index
unordered_map<char, int>index;
for(int i = 0; i < n; i++)index[target[i]] = i;
//按照target的顺序制作Hash
vector<int>Hash(n);
for(int i = 0; i < croakOfFrogs.size(); i++)
{
if(croakOfFrogs[i] == 'c')
{
if(Hash[n-1] != 0)Hash[n-1]--;
Hash[0]++;
}
else
{
//获取当前 croak 字母的下标
int char_index = index[croakOfFrogs[i]];
//判断前一个字符是否在Hash中出现
if(Hash[char_index - 1] == 0)return -1;
Hash[char_index - 1]--; Hash[char_index]++;
}
}
//怕出现这种croakcro
for(int i = 0; i < n-1; i++)
{
if(Hash[i] != 0)return -1;
}
return Hash[n-1];
}
};