• 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;
    }
    
  • 相关阅读:
    Codeforces 115A- Party(DFS)
    【剑指offer】Q19:二叉树的镜像
    Codeforces Round #244 (Div. 2)D (后缀自己主动机)
    iWatch报错: Authorization request cancled
    [HDU 1421]搬寝室(富有新意的DP)
    hdu 2883 kebab(时间区间压缩 &amp;&amp; dinic)
    bzoj-3524 Couriers
    设计模式
    HDU 5063 Operation the Sequence(暴力)
    报错OPTION SQL_SELECT_LIMIT=
  • 原文地址:https://www.cnblogs.com/huerxiong/p/10498751.html
Copyright © 2020-2023  润新知