题目描述:我们有一些二维坐标,如 “(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:]))]