To get the common letters in two words without repetition

前端 未结 4 685
北海茫月
北海茫月 2021-01-29 10:29

Write the function getCommonLetters(word1, word2) that takes in two words as arguments and returns a new string that contains letters found in both string. Ignore r

4条回答
  •  遥遥无期
    2021-01-29 10:58

    If you want correction to your solution, then the problem is that you return the first common letter that you find. You have to continue searching for common letters and combine them into a result:

    def getCommonLetters(word1, word2):
       res = ""
    
       for letter in word1:
          if letter in word2:
             if letter not in res: # skip if we already found it
                 # don't return yet, but rather accumulate the letters
                 res = res + letter
    
       return res
    

    The solutions suggesting using set can be faster, especially if you are checking long words.

提交回复
热议问题