优选算法第六讲:模拟
- 1.替换所有的问号
- 2.提莫攻击
- 3.Z字形变换
- 4.外观数列
- 5.数青蛙
1.替换所有的问号
链接: link
class Solution {
public:string modifyString(string s) {//遍历字符for(int i = 0; i < s.size(); i++){if(s[i] == '?'){for(char ch = 'a'; ch <= 'z'; ch++){if((i == 0 || s[i-1] != ch) && (i == s.size()-1 || s[i+1] != ch)){s[i] = ch;break;}}}}return s;}
};
2.提莫攻击
链接: link
class Solution {
public:int findPoisonedDuration(vector<int>& timeSeries, int duration) {int ret = 0;for(int left = 0, right = 1; right<timeSeries.size(); left++, right++){int cur = timeSeries[right]-timeSeries[left];if(cur < duration) ret += cur;else ret += duration;}return ret + duration;}
};
3.Z字形变换
链接: link
class Solution {
public:string convert(string s, int numRows) {if(numRows == 1) return s;string ret;//先处理第一行int d = 2*numRows-2;int n = s.size();for(int i = 0; i<n; i+=d) ret += s[i];//再处理中间的情况for(int i = 1; i<numRows-1; i++){for(int left = i, right = d-i; left < n || right<n; left+=d, right+=d){if(left < n) ret += s[left];if(right < n) ret += s[right];}}//最后处理最后一行for(int i = numRows-1; i<n; i+=d) ret += s[i];return ret;}
};
4.外观数列
链接: link
class Solution {
public:string countAndSay(int n) {string s = "1";while(--n){string ret;for(int left = 0, right = 0; right<s.size(); ){//right向后寻找第一个不同的元素while(right < s.size() && s[left] == s[right]) right++;int d = right-left;ret += to_string(d) + s[left];left = right;}s = ret;}return s;}
};
5.数青蛙
链接: link
class Solution {
public:int minNumberOfFrogs(string croakOfFrogs) {string s = "croak";int n = s.size();vector<int> hash(n);//使用数组替代哈希表//创建一个哈希表,用来保存s的下标unordered_map<char, int> index;for(int i = 0; i<n; i++)index[s[i]] = i;for(auto e : croakOfFrogs){if(e == 'c'){if(hash[n-1]) hash[n-1]--;hash[0]++;}else{int i = index[e];if(hash[i-1] == 0) return -1;hash[i-1]--, hash[i]++;}}for(int i = 0; i<hash.size()-1; i++)if(hash[i] != 0)return -1;return hash[n-1];}
};