LeetCode1002.Find Common Characters(查找常用字符 )

1002.Find Common Characters(查找常用字符 )

Description

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.

You may return the answer in any order.


给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

你可以按任意顺序返回答案。

题目链接:https://leetcode.com/problems/find-common-characters/

个人主页:http://redtongue.cn or https://redtongue.github.io/

Difficulty: easy

Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]

Note:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] is a lowercase letter

分析

  • 遍历A的第一项的每个字母ind,逐次做一下操作;
  • 遍历A其他的项,若包含ind,则将该项中的ind去掉;
  • 若A所有的项都包含ind,则将ind加入到ans中;
  • 返回ans。

参考代码

class Solution(object):

def commonChars(self, A):
    ans=[]
    if(len(A)==1):
        return list(A[0])
    index = A[0]
    for ind in index:
        for i in range(1,len(A)):
            if(ind in A[i]):
                position=A[i].index(ind)
                A[i]=A[i][:position]+A[i][position+1:]
            else:
                break
        else:
            ans.append(ind)
    return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值