|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022年11月07日 |
| 4 | + |
| 5 | +URL: https://leetcode.com/problems/ambiguous-coordinates/ |
| 6 | + |
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | + |
| 9 | +FileName: 816-AmbiguousCoordinates |
| 10 | + |
| 11 | +Difficulty: Medium |
| 12 | + |
| 13 | +Desc: |
| 14 | + |
| 15 | +Tag: |
| 16 | + |
| 17 | +See: |
| 18 | + |
| 19 | +""" |
| 20 | +from tool import * |
| 21 | + |
| 22 | + |
| 23 | +class Solution: |
| 24 | + def ambiguousCoordinates(self, s: str) -> List[str]: |
| 25 | + """ |
| 26 | + Runtime: 49 ms, faster than 95.41% |
| 27 | + Memory Usage: 14 MB, less than 55.05% |
| 28 | + 4 <= s.length <= 12 |
| 29 | + s[0] == '(' and s[s.length - 1] == ')'. |
| 30 | + The rest of s are digits. |
| 31 | + """ |
| 32 | + |
| 33 | + def valid(s: str) -> List: |
| 34 | + if len(s) == 1: |
| 35 | + return [s] |
| 36 | + if s[-1] == '0' and s[0] == '0': |
| 37 | + return [] |
| 38 | + elif s[0] == '0': |
| 39 | + return [f"{s[0]}.{''.join(s[1:])}"] |
| 40 | + elif s[-1] == '0': |
| 41 | + return [s] |
| 42 | + else: |
| 43 | + return [s] + [f"{''.join(s[:i])}.{''.join(s[i:])}" for i in range(1, len(s))] |
| 44 | + |
| 45 | + s = list(s)[1:-1] |
| 46 | + ret = [] |
| 47 | + for i in range(1, len(s)): |
| 48 | + l, r = valid(''.join(s[:i])), valid(''.join(s[i:])) |
| 49 | + if l and r: |
| 50 | + for a in l: |
| 51 | + for b in r: |
| 52 | + ret.append(f"({a}, {b})") |
| 53 | + return ret |
| 54 | + |
| 55 | + |
| 56 | +def test(): |
| 57 | + ans = ["(1, 2.3)", "(1, 23)", "(1.2, 3)", "(12, 3)"] |
| 58 | + ret = Solution().ambiguousCoordinates(s="(123)") |
| 59 | + assert equal_list_value(ans, ret) |
| 60 | + |
| 61 | + ans = ["(0, 1.23)", "(0, 12.3)", "(0, 123)", "(0.1, 2.3)", "(0.1, 23)", "(0.12, 3)"] |
| 62 | + ret = Solution().ambiguousCoordinates(s="(0123)") |
| 63 | + assert equal_list_value(ans, ret) |
| 64 | + |
| 65 | + assert Solution().ambiguousCoordinates(s="(00011)") == ["(0, 0.011)", "(0.001, 1)"] |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + test() |
0 commit comments