第二十一天
每日一题
最长平衡字符串
2609. 最长平衡子字符串 - 力扣(LeetCode)
class Solution {
public:
int findTheLongestBalancedSubstring(string s) {
if (s.size() == 0) {
return 0;
}
int ans = 0, n = s.size(), cnt_0 = 0, cnt_1 = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == '0') {
// 说明这是1后的第一个0
if (cnt_1 > 0) {
cnt_0 = 0;
cnt_1 = 0;
}
cnt_0 ++;
}
else {
cnt_1++;
// 1只要不超过0的个数就可以进行计数
if (cnt_1 <= cnt_0) {
ans = max(ans, cnt_1*2);
}
}
}
return ans;
}
};
LeetCode 热题 100
两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map <int,int> map;
for(int i = 0; i < nums.size(); i++) {
// 遍历当前元素,并在map中寻找是否有匹配的key
auto iter = map.find(target - nums[i]);
if(iter != map.end()) {
return {iter->second, i};
}
// 如果没找到匹配对,就把访问过的元素和下标加入到map中
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};