目录
1419. 数青蛙
解析
题解
class Solution {
public:
int minNumberOfFrogs(string croakOfFrogs) {
// 44.专题六_模拟_数青蛙_C++
string t = "croak";
int n = t.size();
vector<int> hash(n); // 用数组来模拟哈希表
unordered_map<char, int> index; // [x, x这个字符对应的下标]
for (int i = 0; i < n; ++i)
index[t[i]] = i;
for (auto ch : croakOfFrogs)
{
if (ch == 'c') // c 字符需要特殊处理
{
if (hash[n-1] != 0) hash[n-1]--;
hash[0]++;
}
else
{
int i = index[ch]; // 找到下标
if (hash[i-1] == 0) return -1; // 前一个没有,所以不符合题意
hash[i-1]--; hash[i]++;
}
}
// 判断前面的字符是不是不为0
for (int i = 0; i < n - 1; ++i)
if(hash[i] != 0)
return -1;
return hash[n-1];
}
};