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

    Description

    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 character in J are distinct.

    My Submission

    int numJewelsInStones(char* J, char* S) {
        int num = 0;
        for(int i = 0; i<strlen(J); i++)
            for(int j = 0; j<strlen(S); j++)
            {
                if(J[i] == S[j])
                    num++;
            }
        return num;
    }
    

    解题思路:

    首先想到使用两层嵌套循环,外层为J,内层为S,遍历S中元素j依次和J的i个元素比较,若相等则计数器加一,最后返回计数器。

    遇到问题:

    刚开始不知道C字符串长度的计算方法,经查阅百度得知可以使用strlen()函数。同时有一个疑问,不清楚指针和数组名是否可以进行同等操作,现在想来应该是一样的。

    Sample Submission

    sample 0 ms submission:

    int numJewelsInStones(char* J, char* S) {
        int result_num = 0;
        char* src = J;
        char* dst = S;
        
    
        int i,j;
        
        if ((J == NULL) || (S = NULL))
            return -1;
        
        for (i=0;i<50;i++)
        {
            if (src[i] == '')
                break;
            for (j=0;j<50;j++)
            {
                if (dst[j] == '')
                    break;
                if (src[i] == dst[j]) {
                    //printf("test %c:%c
    ", src[i], dst[j]);
                    result_num++;
                }
            }
        }
            
            
        return result_num;
    }
    
  • 相关阅读:
    linux学习之uniq
    hive学习05 参数设置
    【python】调用sm.ms图床api接口,实现上传图片并返回url
    【python】列表与数组之间的相互转换
    更新yum源
    要把RAID5创建卷组
    named-checkconf -z /etc/named.conf
    function_exists
    trigger_error
    命名空间
  • 原文地址:https://www.cnblogs.com/huerxiong/p/10498751.html
Copyright © 2011-2022 走看看