|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022年10月29日 |
| 4 | + |
| 5 | +URL: https://leetcode.com/problems/count-items-matching-a-rule/ |
| 6 | + |
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | + |
| 9 | +FileName: 1773-CountItemsMatchingARule |
| 10 | + |
| 11 | +Difficulty: Easy |
| 12 | + |
| 13 | +Desc: |
| 14 | + |
| 15 | +Tag: |
| 16 | + |
| 17 | +See: |
| 18 | + |
| 19 | +""" |
| 20 | +from tool import * |
| 21 | + |
| 22 | + |
| 23 | +class Solution: |
| 24 | + def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: |
| 25 | + """ |
| 26 | + Runtime: 261 ms, faster than 88.21% |
| 27 | + Memory Usage: 20.2 MB, less than 86.36% |
| 28 | + 1 <= items.length <= 10^4 |
| 29 | + 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 |
| 30 | + ruleKey is equal to either "type", "color", or "name". |
| 31 | + All strings consist only of lowercase letters. |
| 32 | + """ |
| 33 | + if ruleKey == 'type': |
| 34 | + i = 0 |
| 35 | + elif ruleKey == 'color': |
| 36 | + i = 1 |
| 37 | + else: |
| 38 | + i = 2 |
| 39 | + return sum(1 for x in items if x[i] == ruleValue) |
| 40 | + |
| 41 | + |
| 42 | +def test(): |
| 43 | + assert Solution().countMatches( |
| 44 | + items=[["phone", "blue", "pixel"], ["computer", "silver", "lenovo"], ["phone", "gold", "iphone"]], |
| 45 | + ruleKey="color", ruleValue="silver") == 1 |
| 46 | + assert Solution().countMatches( |
| 47 | + items=[["phone", "blue", "pixel"], ["computer", "silver", "phone"], ["phone", "gold", "iphone"]], |
| 48 | + ruleKey="type", ruleValue="phone") == 2 |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + test() |
0 commit comments