专栏首页SnailTyanLeetcode 1002. Find Common Characters

Leetcode 1002. Find Common Characters

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

  • Version 1
class Solution:
    def commonChars(self, A):
        n = len(A)
        if n == 1:
            return []
        result = sorted(A[0])
        for i in range(1, n):
            result = common(result, A[i])
        return result


def common(A, B):
    result = []
    B = sorted(B)
    m = len(A)
    n = len(B)
    i = 0
    j = 0
    while i < m and j < n:
        if A[i] < B[j]:
            i += 1
        elif A[i] > B[j]:
            j += 1
        else:
            result.append(A[i])
            i += 1
            j += 1
    return result
  • Version 2
class Solution:
    def commonChars(self, A):
        n = len(A)
        if n == 1:
            return []
        result = list(A[0])
        B = [list(A[i]) for i in range(1, n)]
        for ch in A[0]:
            for i in range(n - 1):
                if ch not in B[i]:
                    result.remove(ch)
                    break
                B[i].remove(ch)
        return result

Reference

  1. https://leetcode.com/problems/find-common-characters/

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • LeetCode Weekly Contest 43解题思路

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.n...

    用户1147447
  • SPOJ1811 LCS - Longest Common Substring(后缀自动机)

    attack
  • LeetCode Weekly Contest 46解题思路

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.n...

    用户1147447
  • LeetCode-14. Longest Common Prefix | 最长公共前缀

    Write a function to find the longest common prefix string amongst an array of st...

    Zoctopus
  • 算法养成记:最长公共前缀

    Write a function to find the longest common prefix string amongst an array of st...

    三哥
  • Leetcode solution 10: Regular Expression Matching

    Given an input string (s) and a pattern (p), implement regular expression matchi...

    包子面试培训
  • HDUOJ----2952Counting Sheep

    Counting Sheep Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/327...

    Gxjun
  • String - 14. Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of st...

    用户5705150
  • 二叉树-LeetCode 235、236、226、230(中序,LCA,DFS)

    给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 ...

    算法工程师之路

扫码关注云+社区

领取腾讯云代金券