zoukankan      html  css  js  c++  java
  • [LeetCode] 771. Jewels and Stones

    You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels.

    The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

    Example 1:

    Input: J = "aA", S = "aAAbbbb"
    Output: 3
    

    Example 2:

    Input: J = "z", S = "ZZ"
    Output: 0
    

    Note:

    • S and J will consist of letters and have length at most 50.
    • The characters in J are distinct.

    J是没有重复字母的字符串,S是可能存在重复的字符串。计算S中所包含的S中和J中都存在的字母的个数。

    对S进行排序再求解,减少在J中的遍历次数

    代码如下:

    class Solution {
    public:
        int numJewelsInStones(string J, string S) {
            int res=0;
            sort(S.begin(),S.end());
            for(int i=0;i<S.size();++i){
                for(int j=0;j<J.size();++j){
                    if(S[i]==J[j]){
                        res++;
                        while(S[i]==S[i+1]){
                            ++i;
                            ++res;
                        }
                    }
                }
            }
        }
    };
  • 相关阅读:
    app启动优化
    CountDownLatch妙用
    匿名内部类为什么有可能造成内存泄漏
    单例模式为什么有可能造成内存泄漏
    左移右移记不住怎么办
    说一说ThreadLocal
    对framework层的一些看法
    双重锁单例
    JMM总结
    关于lock前缀
  • 原文地址:https://www.cnblogs.com/cff2121/p/11212867.html
Copyright © 2011-2022 走看看