816. 模糊坐标

该博客探讨了如何从已去除逗号、小数点和空格的字符串中恢复二维坐标。提供了解题思路和两种解决方案,包括自定义的坐标合法性检查函数以及使用`itertools.product`进行坐标组合的方法。博客重点在于字符串处理和数值验证技巧。
摘要由CSDN通过智能技术生成

题目描述:我们有一些二维坐标,如 “(1, 3)” 或 “(2, 0.5)”,然后我们移除所有逗号,小数点和空格,得到一个字符串S。返回所有可能的原始字符串到一个列表中。
原始的坐标表示法不会存在多余的零,所以不会出现类似于"00", “0.0”, “0.00”, “1.0”, “001”, "00.01"或一些其他更小的数来表示坐标。此外,一个小数点前至少存在一个数,所以也不会出现“.1”形式的数字。
最后返回的列表可以是任意顺序的。而且注意返回的两个数字中间(逗号之后)都有一个空格。
解题思路:将字符串S的数字分为两部分,然后对这两部分可以添加的小数点的位置添加小数点,然后判断他们是否为合法的整数和小数,合法的就两两相互组合,合法意味着:(1)如果是整数不能有前导零(2)如果是小数,整数不能有前导零,小数部分结尾不能有零,代码如下:
版本一:

class Solution:
    def ambiguousCoordinates(self, S: str) -> List[str]:
        def isInteger(s):
            if len(s) > 1 and s[0] == '0':
                return False
            return True
        def isDecimal(s):
            items = s.split('.')
            if not isInteger(items[0]) or items[-1][-1] == '0':
                return False
            return True
        
        res = []
        S = S[1:-1]
        size = len(S)
        for i in range(1, size):
            first = S[:i]
            second = S[i:]
            first_decimal = []
            for j in range(1, len(first)):
                tmp = first[:j] + '.' + first[j:]
                if isDecimal(tmp):
                    first_decimal.append(tmp)
            second_decimal = []
            for j in range(1, len(second)):
                tmp = second[:j] + '.' + second[j:]
                if isDecimal(tmp):
                    second_decimal.append(tmp)
            for f in first_decimal:
                for s in second_decimal:
                    res.append('('+f+', '+s+')')
            if isInteger(first):
                for s in second_decimal:
                    res.append('('+first+', '+s+')')
                if isInteger(second):
                    res.append('('+first+', '+second+')')
            if isInteger(second):
                    for f in first_decimal:
                        res.append('('+f+', '+second+')')
            
        return res
            

版本二是官方的更简洁的实现:

class Solution:
    def ambiguousCoordinates(self, S: str) -> List[str]:
        def make(s):
            size = len(s)
            for i in range(1, size+1):
                left = s[:i]
                right = s[i:]
                if (not left.startswith('0') or left == '0') and not right.endswith('0'):
                    yield left + ('.' if i != size else '') + right
        S = S[1:-1]
        return ["({}, {})".format(*cand) for j in range(1, len(S)) for cand in itertools.product(make(S[:j]), make(S[j:]))]
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值