美文网首页程序员leetcode --- js版本
leetcode-Easy-第14期-数组-Find Commo

leetcode-Easy-第14期-数组-Find Commo

作者: 石头说钱 | 来源:发表于2019-03-11 22:16 被阅读16次

题目

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

数组元素都是小写的字符串,找出数组所有元素,都含有的字母,包含重复的

  • Example
Input: ["bella","label","roller"]
Output: ["e","l","l"]
  • 解法
var commonChars = function(A) {
    var target =A[0].split('')
   
   for(let i=0;i<target.length;i++){
       let flag  =true;
       for(let j=0;j<A.length;j++){
           //对数组其他字符串遍历,发现字符串不包含第一个字符串的某个元素,设置flag为false 
           if(A[j].indexOf(target[i]) ==-1){
               flag = false
           }else{
               // 当有共同元素的时候就将其替换为空,避免下一次匹配到到同一个字符
              A[j] = A[j].replace(target[i],'');
           }
       }
       if(!flag){
           target[i] = null
       }
   }
   return target.filter(item=>item !=null)
};
  • 思路
var arr = ["bella","label","roller"]
target = 'bella' = [b,e,l,l,a]
target[0] = b
arr = [' ella','label', 'roller']
target[1] = e
arr = [' ella','lab l', 'roll r']
target[2] = l
arr = [' ella',' ab l', 'ro l r']
target[3] = l
arr = [' ella',' ab ', 'ro  r']
target[4] = a
arr = [' ell ',' ab ','ro  r']
最后target变成 ' ell '
即可得出不为空的就是他们所共有的字符串

相关文章

网友评论

    本文标题:leetcode-Easy-第14期-数组-Find Commo

    本文链接:https://www.haomeiwen.com/subject/gsgipqtx.html