【发布时间】:2021-02-14 02:42:59
【问题描述】:
给定一个包含一系列 Rs 和 Gs 的字符串,寻找一种按组消除它们的方法。如果字符被分组(至少 2 个),您只能消除。
Example 1: RGRRRGGGRR
v v v
RGRRRGGGRR = RGGGGRR = RRR = {empty}, thus there is a possible solution.
Example 2: GGGRGRGRG
v
GGGRGRGRG = RGRGRG, can no longer find groups, thus there is NO possible solution.
我创建了一个初始递归函数,但即使有可能的解决方案,它也没有解决方案。
def fn(string, start):
l = len(string)
if l-start > 0:
counter, isPop = 0, False
if string[start] == 'R':
while counter + start < l and string[counter + start] == 'R': counter+=1
if counter > 1: # If there is the same letter adjacent to the current letter being checked, it will pop this group.
for i in range(counter):
string.pop(start)
isPop = True
if not isPop and start+counter == l: return False # Returns false if previous action did not pop and
else: return fn(string, 0 if isPop else start+counter) # Letter being checked is the last element (it means
# that there are still elements in the string that can
else: # no longer be grouped and eliminated.
while counter + start < l and string[counter + start] == 'G': counter+=1
if counter > 1:
for i in range(counter):
string.pop(start)
isPop = True
if not isPop and start+counter == len(string): return False
else: return fn(string, 0 if isPop else start+counter)
if string: return False
else: return True
ways = []
string = input()
for j in range(len(string)): # Iterates through every position in the list and calls the fn just to see if it is possible.
if True in ways: # If there is a possible solution, it breaks the loop and prints "possible"
break
ways.append(fn(list(string), j))
if True in ways: print("Possible")
else: print("Impossible")
我的算法不起作用的情况(返回 false 但实际上有办法):
1. GGRRGRRRRGGGGRGRGG
v v v v v v
GGRRGRRRRGGGGRGRGG = GGRRGRRRRRGRGG = GGRRGGRGG = GGRRRGG = GGRRRGG = GGGG = {empty}
2. GRRRGRRRGRRRGRRRGR
v v v v v v
GRRRGRRRGRRRGRRRGR = GRRRGRRRGGRRRGR = GRRRGRRRGGGR = GRRRGRRRR = GGRRRR = RRRR = {empty}
【问题讨论】:
-
您更喜欢没有任何导入的解决方案吗?
-
Imports 很好,只是在寻找一个快速的方法。 cdlane 的方法是目前最快的。我认为 ajax 会继续检查所有可能减慢其进程的解决方案,但到目前为止,这两个条目都运行良好。
标签: python string algorithm recursion search