383. 赎金信C++

Problem: 383. 赎金信

文章目录

解题思路

  1. 建立两个26长度的数组,初始值为0;
  2. 对两封信按照字母顺序进行对应位置的数组元素加一统计;
  3. 对勒索信中非0的数组元素与赎金信中进行比对,若是小于或者等于则是通过,可以构成;

解题方法

使用两个数组raCount和maCount分别计量两封信的小写字母组成个数;

统计结束后,直接用勒索信的每个非空字母位置的元素减去对应的赎金信的位置元素,若能拼凑成功则raCount-maCount必定<=0,反之则是raCount-maCount>0的时候就是无法拼凑成功,直接返回false;

如果全部通过,则返回true;

复杂度

时间复杂度:

时间复杂度: O ( l e n R + l e n M + 26 ) O(lenR + lenM + 26) O(lenR+lenM+26)

空间复杂度:

空间复杂度: O ( 52 ) = O ( 1 ) O(52)=O(1) O(52)=O(1)

Code

cpp 复制代码
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int raCount[26]={0},maCount[26]={0};
        int lenR=ransomNote.size();
        int lenM=magazine.size();
        for(int i=0;i<lenR;i++){
            raCount[(ransomNote[i]-'a')]++;
        }
        for(int i=0;i<lenM;i++){
            maCount[(magazine[i]-'a')]++;
        }
        for(int i=0;i<26;i++){
            if(raCount[i]!=0 && (raCount[i]-maCount[i])>0)
            return false;
        }
        return true;
    }
};

Code优化

其实可以只使用一个统计数组,先将赎金信的字母统计加入,在按照勒索信的需求减去,如果有不足,对应的数组元素就小于0

空间复杂度: O ( 26 ) = O ( 1 ) O(26)=O(1) O(26)=O(1)

cpp 复制代码
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int maCount[26]={0};
        int lenR=ransomNote.size();
        int lenM=magazine.size();
        for(int i=0;i<lenM;i++){
            maCount[(magazine[i]-'a')]++;
        }
        for(int i=0;i<lenR;i++){
            maCount[(ransomNote[i]-'a')]--;
        }
        for(int i=0;i<26;i++){
            if(maCount[i]<0)
            return false;
        }
        return true;
    }
};
相关推荐
Cccp.1239 小时前
【leetcode】(六) 图和贪心算法
数据结构·算法·leetcode
y1su9 小时前
【Leetcode】1477. 找两个和为目标值且不重叠的子数组
数据结构·后端·算法·leetcode·职场和发展
唠玖馆9 小时前
C++11
c++
云泽80812 小时前
从零搭建 WSL2 + Ubuntu C/C++ 开发环境:原理、实践与底层架构解析
linux·c++·windows·ubuntu·wsl2
不会就选b17 小时前
算法日常・每日刷题--<贪心>14
算法
初願致夕霞18 小时前
C++11:类型推导与完美转发复盘笔记
c++
小猪写代码18 小时前
C++中什么是类,什么是对象
c++
mmmmath_320 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z20 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode