Fifth algorithm-Gem and stone algorithm

Source: Internet
Author: User

    1. Topic

      The given string J represents the type of gem in the stone, and S the string represents the stone you own.  SEach character represents a type of stone you have, and you want to know how many of the stones you have are gems. The J letters in are not repeated, J and all the S characters in are letters. Letters are case-sensitive, so "a" and "A" are different types of stones.

    2. Analysis
      Give two strings, comparing the number of repetitions of a string in the data in another string

      • Requirements:
        Case-sensitive letters
        Total number of claims
    3. Test data
      Input: J = "aA", S = "aAAbbbb" output: 3
      Input: J = "z", S = "ZZ" output: 0

    4. Reference answer
      Algorithm idea:

      • First, we find the number of stones in s that are repeated in the array
      • The traversal data is compared with the characters in J.
      • public int Numjewelsinstones (string J, String S) {
        int count = 0;
        map<string,integer> map = new hashmap<string,integer> ();
        for (int i =0;i<s.length (); i++) {
        String SV = string.valueof (S.charat (i));
        if (Map.containskey (SV)) {
        Map.put (Sv,map.get (SV) +1);
        }else{
        Map.put (sv,1);
        }
        }

        for (int i =0;i<j.length (); i++) {

        Char s =j.charat (i);
        Count=map.get (string.valueof (s)) ==null?0+count:map.get (string.valueof (s)) +count;
        }
        return count;
        }

5, Excellent solution

        

Class Solution {
public int Numjewelsinstones (string J, String S) {
int result = 0;
Char[] s = new char[128];
for (char C:s.tochararray ()) {
s[c]++;
}
for (char J:j.tochararray ()) {
Result + = S[j];
}
return result;
}
}

Fifth algorithm-Gem and stone algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.