浅谈 宝石与石头 问题

宝石与石头

给定字符串 J 代表石头中宝石的类型,和字符串 S 代表你拥有的石头。S 中每个字符代表了一种你拥有的石头的类型。
返回石头中宝石个数。
J 中的字母不重复,J 和 S 中的所有字符都是字母。字母区分大小写,因此 “a” 和 “A” 是不同类型的石头。

思路:
取出 S 中的每一个字符,与 J 中每一个字符遍历,如果有相同,则宝石加一。

class Solution {
    
    
public:
    int const numJewelsInStones(const string& jewels, const string& stones) {
    
    
        int count = 0;
        int const m = stones.length();
        int const n = jewels.length();
        for(int i = 0; i < m; ++i){
    
    
            for(int j = 0; j < n; ++j){
    
    
                if(stones[i] == jewels[j]){
    
    
                    count++;
                    break;
                }
            }
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_48033173/article/details/112161502
今日推荐