problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::strong_password_checker::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static int strongPasswordChecker (const string &password)
 

详细描述

在文件 leetcode.h2007 行定义.

成员函数说明

◆ strongPasswordChecker()

int leetcode::strong_password_checker::Solution::strongPasswordChecker ( const string &  password)
static

在文件 leetcode.cpp5373 行定义.

5373 {
5374 const int n = password.length();
5375 bool has_lower = false;
5376 bool has_upper = false;
5377 bool has_digit = false;
5378 for(const char ch: password) {
5379 if(islower(ch) != 0) {
5380 has_lower = true;
5381 } else if(isupper(ch) != 0) {
5382 has_upper = true;
5383 } else if(isdigit(ch) != 0) {
5384 has_digit = true;
5385 }
5386 }
5387 const int categories = static_cast<int>(has_lower) + static_cast<int>(has_upper) + static_cast<int>(has_digit);
5388
5389 if(n < 6) {
5390 return max(6 - n, 3 - categories);
5391 }
5392 if(n <= 20) {
5393 int replace = 0;
5394 int count = 0;
5395 char current = '#';
5396
5397 for(const char ch: password) {
5398 if(ch == current) {
5399 ++count;
5400 } else {
5401 replace += count / 3;
5402 count = 1;
5403 current = ch;
5404 }
5405 }
5406 replace += count / 3;
5407 return max(replace, 3 - categories);
5408 }
5409 // 替换次数和删除次数
5410 int replace = 0;
5411 int remove = n - 20;
5412 // k mod 3 = 1 的组数,即删除 2 个字符可以减少 1 次替换操作
5413 int rm2 = 0;
5414 int count = 0;
5415 char cur = '#';
5416
5417 for(const char ch: password) {
5418 if(ch == cur) {
5419 ++count;
5420 } else {
5421 if(remove > 0 && count >= 3) {
5422 if(count % 3 == 0) {
5423 // 如果是 k % 3 = 0 的组,那么优先删除 1 个字符,减少 1 次替换操作
5424 --remove;
5425 --replace;
5426 } else if(count % 3 == 1) {
5427 // 如果是 k % 3 = 1 的组,那么存下来备用
5428 ++rm2;
5429 }
5430 // k % 3 = 2 的组无需显式考虑
5431 }
5432 replace += count / 3;
5433 count = 1;
5434 cur = ch;
5435 }
5436 }
5437 if(remove > 0 && count >= 3) {
5438 if(count % 3 == 0) {
5439 --remove;
5440 --replace;
5441 } else if(count % 3 == 1) {
5442 ++rm2;
5443 }
5444 }
5445 replace += count / 3;
5446
5447 // 使用 k % 3 = 1 的组的数量,由剩余的替换次数、组数和剩余的删除次数共同决定
5448 const int use2 = min({replace, rm2, remove / 2});
5449 replace -= use2;
5450 remove -= use2 * 2;
5451 // 由于每有一次替换次数就一定有 3 个连续相同的字符(k / 3 决定),因此这里可以直接计算出使用 k % 3 = 2 的组的数量
5452 const int use3 = min(replace, remove / 3);
5453 replace -= use3;
5454 remove -= use3 * 3;
5455 return n - 20 + max(replace, 3 - categories);
5456 }
void remove(TreeNode *&root, int x)
Definition: acwing408.cpp:476

引用了 acwing::acwing3786::remove().

被这些函数引用 leetcode::strong_password_checker::TEST().


该类的文档由以下文件生成: