力扣打卡第十六天 模糊坐标

模糊坐标

我们有一些二维坐标,如 “(1, 3)” 或 “(2, 0.5)”,然后我们移除所有逗号,小数点和空格,得到一个字符串S。返回所有可能的原始字符串到一个列表中。最后返回的列表可以是任意顺序的。而且注意返回的两个数字中间(逗号之后)都有一个空格。

方法:枚举
题目给出字符串 sss 为某些原始坐标字符串去掉所有逗号,小数点和空格后得到的字符串,其中需要满足原始坐标表示中的数不会存在多余的零。现在我们要求出所有能生成字符串 sss 的所有可能的原始字符串。 我们可以尝试将原始坐标字符串中去掉的逗号,小数点和空格进行还原——首先在字符串 sss 中枚举添加逗号和空格的位置,将 sss 的数字部分为两个部分,前一部分为原始坐标 xxx 坐标去掉(若存在)小数点后的数字,后一部分为原始坐标 yyy 坐标去掉(若存在)小数点后的数字。

class Solution:
    def ambiguousCoordinates(self, s: str) -> List[str]:
        def get_pos(s: str) -> List[str]:
            pos = []
            if s[0] != '0' or s == '0':
                pos.append(s)
            for p in range(1, len(s)):
                if p != 1 and s[0] == '0' or s[-1] == '0':
                    continue
                pos.append(s[:p] + '.' + s[p:])
            return pos

        n = len(s) - 2
        res = []
        s = s[1: len(s) - 1]
        for l in range(1, n):
            lt = get_pos(s[:l])
            if len(lt) == 0:
                continue
            rt = get_pos(s[l:])
            if len(rt) == 0:
                continue
            for i, j in product(lt, rt):
                res.append('(' + i + ', ' + j + ')')
        return res

猜你喜欢

转载自blog.csdn.net/qq_46157589/article/details/127723677