算法——Week4

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字符串就能得出结果。时间复杂度为O(m*n)


代码如下:

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        int result[S.length()] = {0};
        for(int i = 0; i < S.length(); i++) {
            for(int j = 0; j < J.length(); j++) {
                if(S[i] == J[j]) {
                    result[i] = 1;
                    break;
                }
            }
        }
        int sum = 0;
        for(int i = 0; i < S.length(); i++) {
            sum = sum + result[i];
        }
        return sum;
    }
};

看到别人的解题思路,发现了时间复杂度为O(m+n)的方法:
先遍历J字符串,出现的字符对应的标记为置为1。再遍历S字符串,累加每一个字符对应的标记位。实现如下:

int numJewelsInStones(string J, string S) {
        int  a      = 0;
        //标记位
        char t[128] = {};
        //遍历J,出现的字符标记位置1
        for (char& c : J) t[c] = (char) 1;
        //遍历S,累加
        //c++中数组下标可以为char型,默认为对应的ASCALL码
        for (char& c : S) a    = a + t[c];
        
        return a;
    }

猜你喜欢

转载自blog.csdn.net/melwx/article/details/85272059
今日推荐