复试 || 就业day13(2024.01.09)算法篇

文章目录

  • 前言
  • 统计一致字符串的数目
  • 盒子中小球的最大数量
  • 唯一元素的和
  • 最长的美好子字符串***
  • 仅执行一次字符串交换能否使两个字符串相等

前言

你好,我是辰chen,本文旨在准备考研复试或就业
文章题目大多来自于 leetcode,当然也可能来自洛谷或其他刷题平台
欢迎大家的关注,我的博客主要关注于考研408以及AIoT的内容
仅给出C++版代码

以下的几个专栏是本人比较满意的专栏(大部分专栏仍在持续更新),欢迎大家的关注:

ACM-ICPC算法汇总【基础篇】
ACM-ICPC算法汇总【提高篇】
AIoT(人工智能+物联网)
考研
CSP认证考试历年题解

统计一致字符串的数目


题目链接:统计一致字符串的数目

C++版AC代码:

class Solution {
public:
    int countConsistentStrings(string allowed, vector<string>& words) {
        unordered_map<char, int> m;
        for (auto x : allowed) m[x] = 1;
        int res = 0;
        for (auto word : words) {
            bool flag = true;
            for (auto x : word)
                if (!m.count(x)) {
                    flag = false;
                    break;
                }
            if (flag) res ++;
        }
        return res;
    }
};

盒子中小球的最大数量


题目链接:盒子中小球的最大数量

C++版AC代码:

class Solution {
public:
    int getnum(int n) {
        int num = 0;
        while (n) {
            num += n % 10;
            n /= 10;
        }
        return num;
    }
    int countBalls(int lowLimit, int highLimit) {        
        unordered_map<int, int> m;
        for (int i = lowLimit; i <= highLimit; i ++ ) 
            m[getnum(i)] ++;
        int res = 0;
        for (auto x : m) {
            int k = x.second;
            res = max(res, k);
        }
        return res;
    }
};

唯一元素的和


题目链接:唯一元素的和

C++版AC代码:

class Solution {
public:
    int sumOfUnique(vector<int>& nums) {
        unordered_map<int, int> m;
        for (auto x : nums) m[x] ++;
        int res = 0;
        for (auto x : m)
            if (x.second == 1)
                res += x.first;
        return res;
    }
};

最长的美好子字符串***


题目链接:最长的美好子字符串

C++版AC代码:

滑动窗口的代码后补



仅执行一次字符串交换能否使两个字符串相等


题目链接:仅执行一次字符串交换能否使两个字符串相等

C++版AC代码:

class Solution {
public:
    bool areAlmostEqual(string s1, string s2) {
        int cnt = 0;
        char different[2];
        bool flag = false;
        for (int i = 0; i < s1.size(); i ++ ) 
            if (s1[i] != s2[i] && flag) {   // 第二次失配
                cnt ++;
                if (different[1] != s1[i] || different[0] != s2[i]) return false;
            }
            else if (s1[i] != s2[i] && !flag) {  // 第一次失配
                cnt ++;
                flag = true;
                different[0] = s1[i], different[1] = s2[i];
            }
        if (cnt == 0 || cnt == 2) return true;
        return false;
    }
};

你可能感兴趣的:(考研,#,机试,力扣(LeetCode),算法,复试,cpp,哈希,机试,手撕代码,力扣)