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;
    }
    
  • 相关阅读:
    C#设计模式(6)——原型模式(Prototype Pattern)
    C#设计模式(4)——抽象工厂模式
    C#设计模式(3)——工厂方法模式
    C#设计模式(2)——简单工厂模式
    cmd 打 jar 包
    java eclipse 中给args 传递参数
    java 中值传递和引用传递(转)
    java unreachable code不可达代码
    java语言中if语句的用法
    java中 构造器与void
  • 原文地址:https://www.cnblogs.com/huerxiong/p/10498751.html
Copyright © 2011-2022 走看看