LeetCode “Jewels and Stones”: counting certain characters in a string Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?HackerRank “Manasa and Stones” in PythonCounting all substrings with exactly k distinct charactersFinding maximum length of continuous string which has same charactersStudent Class in C++ using sstream for formatCheck if string is or can be made into a “valid string”Strings: Making AnagramsLeetcode number of atoms solution using stackLeetcode: String to Integer (atoi)Counting ambiguous Morse Code encodings, with and without Java StreamsNon repeating character in Java

Effects on objects due to a brief relocation of massive amounts of mass

What are the diatonic extended chords of C major?

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

If Windows 7 doesn't support WSL, then what does Linux subsystem option mean?

Generate an RGB colour grid

Illegal assignment from sObject to Id

What's the meaning of "fortified infraction restraint"?

How do I use the new nonlinear finite element in Mathematica 12 for this equation?

How much damage would a cupful of neutron star matter do to the Earth?

AppleTVs create a chatty alternate WiFi network

How come Sam didn't become Lord of Horn Hill?

How were pictures turned from film to a big picture in a picture frame before digital scanning?

Why wasn't DOSKEY integrated with COMMAND.COM?

How to compare two different files line by line in unix?

Putting class ranking in CV, but against dept guidelines

Drawing without replacement: why is the order of draw irrelevant?

What is this clumpy 20-30cm high yellow-flowered plant?

Why does the remaining Rebel fleet at the end of Rogue One seem dramatically larger than the one in A New Hope?

Chinese Seal on silk painting - what does it mean?

Maximum summed subsequences with non-adjacent items

Is CEO the "profession" with the most psychopaths?

How can I reduce the gap between left and right of cdot with a macro?

How do I find out the mythology and history of my Fortress?

Do any jurisdictions seriously consider reclassifying social media websites as publishers?



LeetCode “Jewels and Stones”: counting certain characters in a string



Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?HackerRank “Manasa and Stones” in PythonCounting all substrings with exactly k distinct charactersFinding maximum length of continuous string which has same charactersStudent Class in C++ using sstream for formatCheck if string is or can be made into a “valid string”Strings: Making AnagramsLeetcode number of atoms solution using stackLeetcode: String to Integer (atoi)Counting ambiguous Morse Code encodings, with and without Java StreamsNon repeating character in Java



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5












$begingroup$


LeetCode "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.




My approach:



class Solution 
public int numJewelsInStones(String J, String S)

int count = 0;
for( int i = 0; i < J.length(); i++ )

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

if( J.charAt(i) == S.charAt(j) )
count++;


return count;




Time complexity: O(n^2)



Space complexity: O(1)



Another approach:



class Solution 
public int numJewelsInStones(String J, String S)
Set<Character> jSet = new HashSet<>();
for(Character ch : J.toCharArray())
jSet.add(ch);

int count = 0;
for(Character ch: S.toCharArray())
if(jSet.contains(ch))
count++;


return count;




Time complexity: O(n)
Space complexity: O(n)



I have the following questions regarding the above code snippets:



  1. Which approach is better according to you?


  2. Will the interviewer be more impressed by the 2nd method as it has used Set?


  3. How can I further improve my code (sort the string and perform a binary search)-> O(n*log(n))?










share|improve this question











$endgroup$


















    5












    $begingroup$


    LeetCode "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.




    My approach:



    class Solution 
    public int numJewelsInStones(String J, String S)

    int count = 0;
    for( int i = 0; i < J.length(); i++ )

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

    if( J.charAt(i) == S.charAt(j) )
    count++;


    return count;




    Time complexity: O(n^2)



    Space complexity: O(1)



    Another approach:



    class Solution 
    public int numJewelsInStones(String J, String S)
    Set<Character> jSet = new HashSet<>();
    for(Character ch : J.toCharArray())
    jSet.add(ch);

    int count = 0;
    for(Character ch: S.toCharArray())
    if(jSet.contains(ch))
    count++;


    return count;




    Time complexity: O(n)
    Space complexity: O(n)



    I have the following questions regarding the above code snippets:



    1. Which approach is better according to you?


    2. Will the interviewer be more impressed by the 2nd method as it has used Set?


    3. How can I further improve my code (sort the string and perform a binary search)-> O(n*log(n))?










    share|improve this question











    $endgroup$














      5












      5








      5


      3



      $begingroup$


      LeetCode "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.




      My approach:



      class Solution 
      public int numJewelsInStones(String J, String S)

      int count = 0;
      for( int i = 0; i < J.length(); i++ )

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

      if( J.charAt(i) == S.charAt(j) )
      count++;


      return count;




      Time complexity: O(n^2)



      Space complexity: O(1)



      Another approach:



      class Solution 
      public int numJewelsInStones(String J, String S)
      Set<Character> jSet = new HashSet<>();
      for(Character ch : J.toCharArray())
      jSet.add(ch);

      int count = 0;
      for(Character ch: S.toCharArray())
      if(jSet.contains(ch))
      count++;


      return count;




      Time complexity: O(n)
      Space complexity: O(n)



      I have the following questions regarding the above code snippets:



      1. Which approach is better according to you?


      2. Will the interviewer be more impressed by the 2nd method as it has used Set?


      3. How can I further improve my code (sort the string and perform a binary search)-> O(n*log(n))?










      share|improve this question











      $endgroup$




      LeetCode "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.




      My approach:



      class Solution 
      public int numJewelsInStones(String J, String S)

      int count = 0;
      for( int i = 0; i < J.length(); i++ )

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

      if( J.charAt(i) == S.charAt(j) )
      count++;


      return count;




      Time complexity: O(n^2)



      Space complexity: O(1)



      Another approach:



      class Solution 
      public int numJewelsInStones(String J, String S)
      Set<Character> jSet = new HashSet<>();
      for(Character ch : J.toCharArray())
      jSet.add(ch);

      int count = 0;
      for(Character ch: S.toCharArray())
      if(jSet.contains(ch))
      count++;


      return count;




      Time complexity: O(n)
      Space complexity: O(n)



      I have the following questions regarding the above code snippets:



      1. Which approach is better according to you?


      2. Will the interviewer be more impressed by the 2nd method as it has used Set?


      3. How can I further improve my code (sort the string and perform a binary search)-> O(n*log(n))?







      java beginner programming-challenge comparative-review






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 3 '18 at 18:06









      200_success

      131k17157422




      131k17157422










      asked May 3 '18 at 9:09









      Anirudh ThatipelliAnirudh Thatipelli

      283313




      283313




















          5 Answers
          5






          active

          oldest

          votes


















          6












          $begingroup$

          Caution — naïve application of big-O analysis will lead you astray here!



          First of all, you should be more precise about what you mean by "n". In this problem, there are |J| and |S|: the lengths of J and S. Your first approach is O(|J| |S|); your second one is O(|J| + |S|).



          More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs. In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards. That means that the constant factors, which are disregarded in big-O analysis, actually matter. (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)



          Consider how much code is involved in making a HashSet. A HashSet is actually a disguise for a HashMap. A HashMap is implemented as an array of trees, each containing Map.Entry objects. The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor. Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table. The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!



          Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:



          public int numJewelsInStones(String j, String s) 
          boolean[] jewels = new boolean[128];
          for (int i = 0; i < j.length(); i++)
          jewels[j.codePointAt(i)] = true;

          int count = 0;
          for (int i = 0; i < s.length(); i++)
          if (jewels[s.codePointAt(i)])
          count++;


          return count;






          share|improve this answer









          $endgroup$




















            4












            $begingroup$

            Not much time, so just in short:



            1. Definitely the second. It shows that you have got at least a general grip on datastructures (knowing the complexity of HashSet operations) and know a bit about the standard library. Regarding the fist one: this even uses a loop instead of indexOf - I'd immediatly show you to the door for that, if I were the interviewer...

            2. Second is definitely better, but not impressive eiher. Try getting a grip on the stream API and play around with String.codePoints - my own try-that-for-comparison-solution was 2 lines using this...

            3. You shouldn't. From my opinion, it is OK to explain in addition that there might be a possible solution using binary search over the stones string, which completes in $O(ntimes log(n))$, but I would not to see an even longer solution for micro-optimizing a simple problem which takes milliseconds to execute. Simplicity, readability and clarity are the key attributes.





            share|improve this answer









            $endgroup$












            • $begingroup$
              Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
              $endgroup$
              – Anirudh Thatipelli
              May 3 '18 at 10:27


















            3












            $begingroup$



            You could speed up the first version by switching the loops, so that the loop over J becomes the inner loop, and short-circuiting the loop over J, because once you have found a character in J that matches the current character in S, you don't have to loop over the remaining characters of J (mtj's suggestion to use String.indexOf(char) would amount to this).



            As for the second approach: Why do you first convert the strings to a char[] before iterating over their characters? You did not do this in the first version, so what do you gain from it by doing it in the second version?



            About your question which approach is better: Depends on what you mean by better. I think both versions are quite straighforward and to the point. For large strings, the second version might be preferable because it has a lower time complexity. However, you write that the strings will contain at most 50 characters, so the benefit of constant-time lookup might not outweigh the cost of creating a Set and implicitly converting each primitive char to a Character object. But this is just a guess, I did not measure it.






            share|improve this answer











            $endgroup$












            • $begingroup$
              Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
              $endgroup$
              – Anirudh Thatipelli
              May 3 '18 at 10:25










            • $begingroup$
              @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
              $endgroup$
              – Stingy
              May 3 '18 at 10:35










            • $begingroup$
              I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
              $endgroup$
              – Anirudh Thatipelli
              May 3 '18 at 10:37











            • $begingroup$
              @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
              $endgroup$
              – Stingy
              May 3 '18 at 10:47










            • $begingroup$
              Oh right. I may have been confusing time complexity with speed!!
              $endgroup$
              – Anirudh Thatipelli
              May 3 '18 at 10:49


















            0












            $begingroup$

            This code is in Python 3.0 version.
            It takes each character in stones S first and checks if it is present in Jewels J, if present, it increses the count by 1 and then returns the total count.



            class Solution:
            def numJewelsInStones(self, J: str, S: str) -> int:
            jewels = 0
            for char in S:
            if char in J:
            jewels += 1



            return jewels




            share








            New contributor




            Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            $endgroup$




















              -1












              $begingroup$

              public long numJewelsInStones(String J, String S) 
              Set<Character> jewels = J.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
              return jewels.stream().filter(x -> S.contains(x + "")).count();



              Definitely, second approach is better, java 8 can actually truncate it further.
              Also jewels is a better name than jSet.






              share|improve this answer









              $endgroup$








              • 1




                $begingroup$
                I think this is wrong, as it only counts each jewel once?
                $endgroup$
                – Koekje
                May 3 '18 at 13:41










              • $begingroup$
                Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                $endgroup$
                – Anirudh Thatipelli
                May 3 '18 at 15:20










              • $begingroup$
                @Koekje letters in J are guaranteed distinct right ?
                $endgroup$
                – Tanvi Jaywant
                May 3 '18 at 16:22










              • $begingroup$
                @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                $endgroup$
                – Koekje
                May 3 '18 at 16:48











              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "196"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193538%2fleetcode-jewels-and-stones-counting-certain-characters-in-a-string%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              6












              $begingroup$

              Caution — naïve application of big-O analysis will lead you astray here!



              First of all, you should be more precise about what you mean by "n". In this problem, there are |J| and |S|: the lengths of J and S. Your first approach is O(|J| |S|); your second one is O(|J| + |S|).



              More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs. In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards. That means that the constant factors, which are disregarded in big-O analysis, actually matter. (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)



              Consider how much code is involved in making a HashSet. A HashSet is actually a disguise for a HashMap. A HashMap is implemented as an array of trees, each containing Map.Entry objects. The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor. Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table. The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!



              Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:



              public int numJewelsInStones(String j, String s) 
              boolean[] jewels = new boolean[128];
              for (int i = 0; i < j.length(); i++)
              jewels[j.codePointAt(i)] = true;

              int count = 0;
              for (int i = 0; i < s.length(); i++)
              if (jewels[s.codePointAt(i)])
              count++;


              return count;






              share|improve this answer









              $endgroup$

















                6












                $begingroup$

                Caution — naïve application of big-O analysis will lead you astray here!



                First of all, you should be more precise about what you mean by "n". In this problem, there are |J| and |S|: the lengths of J and S. Your first approach is O(|J| |S|); your second one is O(|J| + |S|).



                More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs. In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards. That means that the constant factors, which are disregarded in big-O analysis, actually matter. (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)



                Consider how much code is involved in making a HashSet. A HashSet is actually a disguise for a HashMap. A HashMap is implemented as an array of trees, each containing Map.Entry objects. The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor. Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table. The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!



                Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:



                public int numJewelsInStones(String j, String s) 
                boolean[] jewels = new boolean[128];
                for (int i = 0; i < j.length(); i++)
                jewels[j.codePointAt(i)] = true;

                int count = 0;
                for (int i = 0; i < s.length(); i++)
                if (jewels[s.codePointAt(i)])
                count++;


                return count;






                share|improve this answer









                $endgroup$















                  6












                  6








                  6





                  $begingroup$

                  Caution — naïve application of big-O analysis will lead you astray here!



                  First of all, you should be more precise about what you mean by "n". In this problem, there are |J| and |S|: the lengths of J and S. Your first approach is O(|J| |S|); your second one is O(|J| + |S|).



                  More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs. In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards. That means that the constant factors, which are disregarded in big-O analysis, actually matter. (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)



                  Consider how much code is involved in making a HashSet. A HashSet is actually a disguise for a HashMap. A HashMap is implemented as an array of trees, each containing Map.Entry objects. The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor. Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table. The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!



                  Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:



                  public int numJewelsInStones(String j, String s) 
                  boolean[] jewels = new boolean[128];
                  for (int i = 0; i < j.length(); i++)
                  jewels[j.codePointAt(i)] = true;

                  int count = 0;
                  for (int i = 0; i < s.length(); i++)
                  if (jewels[s.codePointAt(i)])
                  count++;


                  return count;






                  share|improve this answer









                  $endgroup$



                  Caution — naïve application of big-O analysis will lead you astray here!



                  First of all, you should be more precise about what you mean by "n". In this problem, there are |J| and |S|: the lengths of J and S. Your first approach is O(|J| |S|); your second one is O(|J| + |S|).



                  More importantly, big-O analysis only tells you how well an algorithm scales to handle large inputs. In this challenge, though, |J| and |S| are at most 50 — very small inputs, by computer standards. That means that the constant factors, which are disregarded in big-O analysis, actually matter. (Another way to look at it: with those limits, |J| and |S| are both O(1), so any sane solution is also O(1)!)



                  Consider how much code is involved in making a HashSet. A HashSet is actually a disguise for a HashMap. A HashMap is implemented as an array of trees, each containing Map.Entry objects. The array should be optimally sized to hold all the characters of J with no hashcode collisions, but you neglected to specify size hints when calling the HashSet<>() constructor. Then, you have to insert each character of J, which involves boxing a char into a Character, calculating its hashcode, making a Map.Entry for it, and inserting it into the HashMap's table. The problem is, Java makes it easy to execute a lot of operations without making you aware of how much work it actually is!



                  Since the challenge states that all characters are letters — which I interpret to mean the 52 letters in the English alphabet, you could achieve an efficient test of membership in J using a simple lookup table:



                  public int numJewelsInStones(String j, String s) 
                  boolean[] jewels = new boolean[128];
                  for (int i = 0; i < j.length(); i++)
                  jewels[j.codePointAt(i)] = true;

                  int count = 0;
                  for (int i = 0; i < s.length(); i++)
                  if (jewels[s.codePointAt(i)])
                  count++;


                  return count;







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 3 '18 at 18:35









                  200_success200_success

                  131k17157422




                  131k17157422























                      4












                      $begingroup$

                      Not much time, so just in short:



                      1. Definitely the second. It shows that you have got at least a general grip on datastructures (knowing the complexity of HashSet operations) and know a bit about the standard library. Regarding the fist one: this even uses a loop instead of indexOf - I'd immediatly show you to the door for that, if I were the interviewer...

                      2. Second is definitely better, but not impressive eiher. Try getting a grip on the stream API and play around with String.codePoints - my own try-that-for-comparison-solution was 2 lines using this...

                      3. You shouldn't. From my opinion, it is OK to explain in addition that there might be a possible solution using binary search over the stones string, which completes in $O(ntimes log(n))$, but I would not to see an even longer solution for micro-optimizing a simple problem which takes milliseconds to execute. Simplicity, readability and clarity are the key attributes.





                      share|improve this answer









                      $endgroup$












                      • $begingroup$
                        Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:27















                      4












                      $begingroup$

                      Not much time, so just in short:



                      1. Definitely the second. It shows that you have got at least a general grip on datastructures (knowing the complexity of HashSet operations) and know a bit about the standard library. Regarding the fist one: this even uses a loop instead of indexOf - I'd immediatly show you to the door for that, if I were the interviewer...

                      2. Second is definitely better, but not impressive eiher. Try getting a grip on the stream API and play around with String.codePoints - my own try-that-for-comparison-solution was 2 lines using this...

                      3. You shouldn't. From my opinion, it is OK to explain in addition that there might be a possible solution using binary search over the stones string, which completes in $O(ntimes log(n))$, but I would not to see an even longer solution for micro-optimizing a simple problem which takes milliseconds to execute. Simplicity, readability and clarity are the key attributes.





                      share|improve this answer









                      $endgroup$












                      • $begingroup$
                        Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:27













                      4












                      4








                      4





                      $begingroup$

                      Not much time, so just in short:



                      1. Definitely the second. It shows that you have got at least a general grip on datastructures (knowing the complexity of HashSet operations) and know a bit about the standard library. Regarding the fist one: this even uses a loop instead of indexOf - I'd immediatly show you to the door for that, if I were the interviewer...

                      2. Second is definitely better, but not impressive eiher. Try getting a grip on the stream API and play around with String.codePoints - my own try-that-for-comparison-solution was 2 lines using this...

                      3. You shouldn't. From my opinion, it is OK to explain in addition that there might be a possible solution using binary search over the stones string, which completes in $O(ntimes log(n))$, but I would not to see an even longer solution for micro-optimizing a simple problem which takes milliseconds to execute. Simplicity, readability and clarity are the key attributes.





                      share|improve this answer









                      $endgroup$



                      Not much time, so just in short:



                      1. Definitely the second. It shows that you have got at least a general grip on datastructures (knowing the complexity of HashSet operations) and know a bit about the standard library. Regarding the fist one: this even uses a loop instead of indexOf - I'd immediatly show you to the door for that, if I were the interviewer...

                      2. Second is definitely better, but not impressive eiher. Try getting a grip on the stream API and play around with String.codePoints - my own try-that-for-comparison-solution was 2 lines using this...

                      3. You shouldn't. From my opinion, it is OK to explain in addition that there might be a possible solution using binary search over the stones string, which completes in $O(ntimes log(n))$, but I would not to see an even longer solution for micro-optimizing a simple problem which takes milliseconds to execute. Simplicity, readability and clarity are the key attributes.






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 3 '18 at 9:28









                      mtjmtj

                      2,979314




                      2,979314











                      • $begingroup$
                        Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:27
















                      • $begingroup$
                        Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:27















                      $begingroup$
                      Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:27




                      $begingroup$
                      Thank you, @mtj for this advice. I had thought that writing extra code for binary search won't be useful enough as it will decrease the overall readability without giving a substantial advantage. I would love to check out String.codePoints.
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:27











                      3












                      $begingroup$



                      You could speed up the first version by switching the loops, so that the loop over J becomes the inner loop, and short-circuiting the loop over J, because once you have found a character in J that matches the current character in S, you don't have to loop over the remaining characters of J (mtj's suggestion to use String.indexOf(char) would amount to this).



                      As for the second approach: Why do you first convert the strings to a char[] before iterating over their characters? You did not do this in the first version, so what do you gain from it by doing it in the second version?



                      About your question which approach is better: Depends on what you mean by better. I think both versions are quite straighforward and to the point. For large strings, the second version might be preferable because it has a lower time complexity. However, you write that the strings will contain at most 50 characters, so the benefit of constant-time lookup might not outweigh the cost of creating a Set and implicitly converting each primitive char to a Character object. But this is just a guess, I did not measure it.






                      share|improve this answer











                      $endgroup$












                      • $begingroup$
                        Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:25










                      • $begingroup$
                        @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:35










                      • $begingroup$
                        I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:37











                      • $begingroup$
                        @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:47










                      • $begingroup$
                        Oh right. I may have been confusing time complexity with speed!!
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:49















                      3












                      $begingroup$



                      You could speed up the first version by switching the loops, so that the loop over J becomes the inner loop, and short-circuiting the loop over J, because once you have found a character in J that matches the current character in S, you don't have to loop over the remaining characters of J (mtj's suggestion to use String.indexOf(char) would amount to this).



                      As for the second approach: Why do you first convert the strings to a char[] before iterating over their characters? You did not do this in the first version, so what do you gain from it by doing it in the second version?



                      About your question which approach is better: Depends on what you mean by better. I think both versions are quite straighforward and to the point. For large strings, the second version might be preferable because it has a lower time complexity. However, you write that the strings will contain at most 50 characters, so the benefit of constant-time lookup might not outweigh the cost of creating a Set and implicitly converting each primitive char to a Character object. But this is just a guess, I did not measure it.






                      share|improve this answer











                      $endgroup$












                      • $begingroup$
                        Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:25










                      • $begingroup$
                        @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:35










                      • $begingroup$
                        I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:37











                      • $begingroup$
                        @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:47










                      • $begingroup$
                        Oh right. I may have been confusing time complexity with speed!!
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:49













                      3












                      3








                      3





                      $begingroup$



                      You could speed up the first version by switching the loops, so that the loop over J becomes the inner loop, and short-circuiting the loop over J, because once you have found a character in J that matches the current character in S, you don't have to loop over the remaining characters of J (mtj's suggestion to use String.indexOf(char) would amount to this).



                      As for the second approach: Why do you first convert the strings to a char[] before iterating over their characters? You did not do this in the first version, so what do you gain from it by doing it in the second version?



                      About your question which approach is better: Depends on what you mean by better. I think both versions are quite straighforward and to the point. For large strings, the second version might be preferable because it has a lower time complexity. However, you write that the strings will contain at most 50 characters, so the benefit of constant-time lookup might not outweigh the cost of creating a Set and implicitly converting each primitive char to a Character object. But this is just a guess, I did not measure it.






                      share|improve this answer











                      $endgroup$





                      You could speed up the first version by switching the loops, so that the loop over J becomes the inner loop, and short-circuiting the loop over J, because once you have found a character in J that matches the current character in S, you don't have to loop over the remaining characters of J (mtj's suggestion to use String.indexOf(char) would amount to this).



                      As for the second approach: Why do you first convert the strings to a char[] before iterating over their characters? You did not do this in the first version, so what do you gain from it by doing it in the second version?



                      About your question which approach is better: Depends on what you mean by better. I think both versions are quite straighforward and to the point. For large strings, the second version might be preferable because it has a lower time complexity. However, you write that the strings will contain at most 50 characters, so the benefit of constant-time lookup might not outweigh the cost of creating a Set and implicitly converting each primitive char to a Character object. But this is just a guess, I did not measure it.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 3 '18 at 9:48

























                      answered May 3 '18 at 9:36









                      StingyStingy

                      1,988212




                      1,988212











                      • $begingroup$
                        Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:25










                      • $begingroup$
                        @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:35










                      • $begingroup$
                        I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:37











                      • $begingroup$
                        @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:47










                      • $begingroup$
                        Oh right. I may have been confusing time complexity with speed!!
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:49
















                      • $begingroup$
                        Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:25










                      • $begingroup$
                        @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:35










                      • $begingroup$
                        I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:37











                      • $begingroup$
                        @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                        $endgroup$
                        – Stingy
                        May 3 '18 at 10:47










                      • $begingroup$
                        Oh right. I may have been confusing time complexity with speed!!
                        $endgroup$
                        – Anirudh Thatipelli
                        May 3 '18 at 10:49















                      $begingroup$
                      Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:25




                      $begingroup$
                      Thanks for your valuable comments, @Stingy. I thought about using binary search and improving my time complexity to O(n*log(n)). What is your take on this? Does sorting create another overhead?
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:25












                      $begingroup$
                      @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                      $endgroup$
                      – Stingy
                      May 3 '18 at 10:35




                      $begingroup$
                      @AnirudhThatipelli I don't quite understand. I would have thought that $O(ncdotlog(n))$ is worse than $O(n)$, since it has an other factor that grows with $n$?
                      $endgroup$
                      – Stingy
                      May 3 '18 at 10:35












                      $begingroup$
                      I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:37





                      $begingroup$
                      I was talking about my first approach. The time complexity is O(n^2) which I can reduce using binary search instead of the inner for loop. But, @mtj's point makes sense here as it would decrease the readability of the code.
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:37













                      $begingroup$
                      @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                      $endgroup$
                      – Stingy
                      May 3 '18 at 10:47




                      $begingroup$
                      @AnirudhThatipelli Again, time complexity and speed are two different things. Time complexity only means how the growth of the input would affect the speed, but it doesn't say anything about how two algorithms will perform compared to each other on the same input. If you want to know which one is faster, you'll have to measure it. But then, with such small input sizes, I doubt that it matters, and as mtj has pointed out, I think simplicity, readability and clarity are more important here than micro-optimizations.
                      $endgroup$
                      – Stingy
                      May 3 '18 at 10:47












                      $begingroup$
                      Oh right. I may have been confusing time complexity with speed!!
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:49




                      $begingroup$
                      Oh right. I may have been confusing time complexity with speed!!
                      $endgroup$
                      – Anirudh Thatipelli
                      May 3 '18 at 10:49











                      0












                      $begingroup$

                      This code is in Python 3.0 version.
                      It takes each character in stones S first and checks if it is present in Jewels J, if present, it increses the count by 1 and then returns the total count.



                      class Solution:
                      def numJewelsInStones(self, J: str, S: str) -> int:
                      jewels = 0
                      for char in S:
                      if char in J:
                      jewels += 1



                      return jewels




                      share








                      New contributor




                      Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.






                      $endgroup$

















                        0












                        $begingroup$

                        This code is in Python 3.0 version.
                        It takes each character in stones S first and checks if it is present in Jewels J, if present, it increses the count by 1 and then returns the total count.



                        class Solution:
                        def numJewelsInStones(self, J: str, S: str) -> int:
                        jewels = 0
                        for char in S:
                        if char in J:
                        jewels += 1



                        return jewels




                        share








                        New contributor




                        Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.






                        $endgroup$















                          0












                          0








                          0





                          $begingroup$

                          This code is in Python 3.0 version.
                          It takes each character in stones S first and checks if it is present in Jewels J, if present, it increses the count by 1 and then returns the total count.



                          class Solution:
                          def numJewelsInStones(self, J: str, S: str) -> int:
                          jewels = 0
                          for char in S:
                          if char in J:
                          jewels += 1



                          return jewels




                          share








                          New contributor




                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          $endgroup$



                          This code is in Python 3.0 version.
                          It takes each character in stones S first and checks if it is present in Jewels J, if present, it increses the count by 1 and then returns the total count.



                          class Solution:
                          def numJewelsInStones(self, J: str, S: str) -> int:
                          jewels = 0
                          for char in S:
                          if char in J:
                          jewels += 1



                          return jewels





                          share








                          New contributor




                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.








                          share


                          share






                          New contributor




                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          answered 2 mins ago









                          Prince PiperaPrince Pipera

                          1




                          1




                          New contributor




                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





                          New contributor





                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          Prince Pipera is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





















                              -1












                              $begingroup$

                              public long numJewelsInStones(String J, String S) 
                              Set<Character> jewels = J.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
                              return jewels.stream().filter(x -> S.contains(x + "")).count();



                              Definitely, second approach is better, java 8 can actually truncate it further.
                              Also jewels is a better name than jSet.






                              share|improve this answer









                              $endgroup$








                              • 1




                                $begingroup$
                                I think this is wrong, as it only counts each jewel once?
                                $endgroup$
                                – Koekje
                                May 3 '18 at 13:41










                              • $begingroup$
                                Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                                $endgroup$
                                – Anirudh Thatipelli
                                May 3 '18 at 15:20










                              • $begingroup$
                                @Koekje letters in J are guaranteed distinct right ?
                                $endgroup$
                                – Tanvi Jaywant
                                May 3 '18 at 16:22










                              • $begingroup$
                                @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                                $endgroup$
                                – Koekje
                                May 3 '18 at 16:48















                              -1












                              $begingroup$

                              public long numJewelsInStones(String J, String S) 
                              Set<Character> jewels = J.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
                              return jewels.stream().filter(x -> S.contains(x + "")).count();



                              Definitely, second approach is better, java 8 can actually truncate it further.
                              Also jewels is a better name than jSet.






                              share|improve this answer









                              $endgroup$








                              • 1




                                $begingroup$
                                I think this is wrong, as it only counts each jewel once?
                                $endgroup$
                                – Koekje
                                May 3 '18 at 13:41










                              • $begingroup$
                                Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                                $endgroup$
                                – Anirudh Thatipelli
                                May 3 '18 at 15:20










                              • $begingroup$
                                @Koekje letters in J are guaranteed distinct right ?
                                $endgroup$
                                – Tanvi Jaywant
                                May 3 '18 at 16:22










                              • $begingroup$
                                @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                                $endgroup$
                                – Koekje
                                May 3 '18 at 16:48













                              -1












                              -1








                              -1





                              $begingroup$

                              public long numJewelsInStones(String J, String S) 
                              Set<Character> jewels = J.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
                              return jewels.stream().filter(x -> S.contains(x + "")).count();



                              Definitely, second approach is better, java 8 can actually truncate it further.
                              Also jewels is a better name than jSet.






                              share|improve this answer









                              $endgroup$



                              public long numJewelsInStones(String J, String S) 
                              Set<Character> jewels = J.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
                              return jewels.stream().filter(x -> S.contains(x + "")).count();



                              Definitely, second approach is better, java 8 can actually truncate it further.
                              Also jewels is a better name than jSet.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 3 '18 at 13:22









                              Tanvi JaywantTanvi Jaywant

                              1122




                              1122







                              • 1




                                $begingroup$
                                I think this is wrong, as it only counts each jewel once?
                                $endgroup$
                                – Koekje
                                May 3 '18 at 13:41










                              • $begingroup$
                                Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                                $endgroup$
                                – Anirudh Thatipelli
                                May 3 '18 at 15:20










                              • $begingroup$
                                @Koekje letters in J are guaranteed distinct right ?
                                $endgroup$
                                – Tanvi Jaywant
                                May 3 '18 at 16:22










                              • $begingroup$
                                @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                                $endgroup$
                                – Koekje
                                May 3 '18 at 16:48












                              • 1




                                $begingroup$
                                I think this is wrong, as it only counts each jewel once?
                                $endgroup$
                                – Koekje
                                May 3 '18 at 13:41










                              • $begingroup$
                                Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                                $endgroup$
                                – Anirudh Thatipelli
                                May 3 '18 at 15:20










                              • $begingroup$
                                @Koekje letters in J are guaranteed distinct right ?
                                $endgroup$
                                – Tanvi Jaywant
                                May 3 '18 at 16:22










                              • $begingroup$
                                @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                                $endgroup$
                                – Koekje
                                May 3 '18 at 16:48







                              1




                              1




                              $begingroup$
                              I think this is wrong, as it only counts each jewel once?
                              $endgroup$
                              – Koekje
                              May 3 '18 at 13:41




                              $begingroup$
                              I think this is wrong, as it only counts each jewel once?
                              $endgroup$
                              – Koekje
                              May 3 '18 at 13:41












                              $begingroup$
                              Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                              $endgroup$
                              – Anirudh Thatipelli
                              May 3 '18 at 15:20




                              $begingroup$
                              Thanks, @Tanvi Jaywant. I will try out your approach as well. I have never used mapTo in Java.
                              $endgroup$
                              – Anirudh Thatipelli
                              May 3 '18 at 15:20












                              $begingroup$
                              @Koekje letters in J are guaranteed distinct right ?
                              $endgroup$
                              – Tanvi Jaywant
                              May 3 '18 at 16:22




                              $begingroup$
                              @Koekje letters in J are guaranteed distinct right ?
                              $endgroup$
                              – Tanvi Jaywant
                              May 3 '18 at 16:22












                              $begingroup$
                              @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                              $endgroup$
                              – Koekje
                              May 3 '18 at 16:48




                              $begingroup$
                              @TanviJaywant correct, but take example 1, J = "aA", S = "aAAbbbb", you will stream over each jewel counting 1 for each that is contained in S. This will return 2, when in fact there are 3 jewels between the stones.
                              $endgroup$
                              – Koekje
                              May 3 '18 at 16:48

















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f193538%2fleetcode-jewels-and-stones-counting-certain-characters-in-a-string%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                              Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar

                              香港授勳及嘉獎制度 目录 勳章及獎狀類別 嘉獎等級 授勳及嘉獎提名 統計數字 多次獲頒勳章或獎狀的人士 爭議 褫奪機制 参考文献 外部連結 参见 导航菜单統計數字一九九七年七月二日(星期三)香港特別行政區的授勳制度六七暴動領袖獲大紫荊勳章 董建華被斥為肯定殺人放火董建華授勳楊光 議員窮追猛打蘋論:顛倒是非黑白的大紫荊董讚楊光有貢獻避談暴動董拒答授勳楊光原因撤除勳銜撤除勳銜撤除勳銜特首掌「搣柴」生殺權行為失當罪 隨時「搣柴」失長糧政府刊憲 許仕仁郭炳江遭「搣柴」去年中終極上訴失敗 許仕仁郭炳江撤勳章太平紳士猛料阿Sir講古—— 「搣柴」有故一九九八年授勳名單一九九九年授勳名單二○○三年授勳名單二○○八年授勳名單二○○七年授勳名單政府總部禮賓處 - 授勳及嘉獎香港特別行政區勳章綬帶一覽(PDF)(非官方)