leetcode 尝试未运行

问题描述 投票:0回答:2
class Solution {
public:

    int numJewelsInStones(string jewels, string stones) {
        unordered_map<string,int>mapOfJewels;
        for(auto pair:jewels){
            mapOfJewels[pair]++;
        }

        unordered_map<string,int>mapOfStones;
        for(auto pair:stones){
            mapOfStones[pair]++;
        }
    }
int counter = 0;
for ( auto count: mapOfJewels){
    string keyToCheck = count.first;
        if(mapOfStones.find(keyToCheck) != mapOfStones.end()){
             counter+= count.second;
        }
}
return counter;
};

代码不断给出错误,我怀疑它可能是循环逻辑,但我不知道,逻辑似乎很好,我继续检查它以确保它正确处理内存,但它不断给我同样的错误,这个是 771 个宝石和石头,(给你字符串 Jewels 代表宝石的类型,stones 代表你拥有的宝石。stones 中的每个字符都是你拥有的石头类型。你想知道有多少个你拥有的石头也是珠宝。)

c++ maps
2个回答
0
投票

函数 numJewelsInStones 的两个参数都是 std::string 类型的对象。

int numJewelsInStones(string jewels, string stones) {

例如在这个范围内基于 for 循环

    for(auto pair:jewels){
        mapOfJewels[pair]++;
    }

变量

pair
的类型为
char
。但是您声明了一个键类型为 std::string

的映射
    unordered_map<string,int>mapOfJewels;

并尝试使用字符

pair
作为 std::string

类型的 cpnstructor
        mapOfJewels[pair]++;

无论 std::string 类没有合适的构造函数。


0
投票
#include <iostream>
#include <unordered_map>

using namespace std;

class Solution {
public:

    int numJewelsInStones(string jewels, string stones) {
        unordered_map<char, int> mapOfJewels;
        for(auto ch : jewels){
            mapOfJewels[ch]++;
        }

        int counter = 0;
        for(auto ch : stones){
            if(mapOfJewels.find(ch) != mapOfJewels.end()){
                counter++;
            }
        }
        return counter;
    }
};

int main() {
    Solution s;
    string jewels = "aA";
    string stones = "aAAbbbb";
    int count = s.numJewelsInStones(jewels, stones);
    std::cout << "Number of jewels in stones: " << count << std::endl;
    return 0;
}

我修复了一些错误并尝试编译它。 您代码中的问题在于“迭代字符串”,就好像它们是“字符容器”。问题在于您尝试使用 unordered_map 计算字符串 Jewels 和 Stones 中字符的出现次数的方式

© www.soinside.com 2019 - 2024. All rights reserved.