Python完美走位

360影视 2025-01-17 10:39 2

摘要:def getResult(s):# 统计 W, A, S, D 四个方向的步数step_count = {"W": 0,"A": 0,"S": 0,"D": 0}for c in s:step_count[c] += 1avg = len(s) / 4 #

def getResult(s):# 统计 W, A, S, D 四个方向的步数step_count = {"W": 0,"A": 0,"S": 0,"D": 0}for c in s:step_count[c] += 1avg = len(s) / 4 # 平衡状态时,每个方向的步数excess_steps = 0 # 记录超过平衡状态的步数is_balanced = True # 标记当前是否为平衡状态for c in step_count:if step_count[c] > avg:is_balanced = Falsestep_count[c] -= avgexcess_steps += step_count[c]else:step_count[c] = 0if is_balanced:return 0 # 如果已经是平衡状态,返回 0i = 0min_len = len(s) # 初始化最小替换长度为字符串长度# 滑动窗口遍历字符串for j in range(len(s)):char = s[j]if step_count[char] > 0:excess_steps -= 1step_count[char] -= 1while excess_steps == 0:min_len = min(min_len, j - i + 1)left_char = s[i]if step_count[left_char] >= 0:excess_steps += 1step_count[left_char] += 1i += 1return min_len# 输入获取s = input.strip# 输出结果print(getResult(s))

来源:寻找游戏的乐趣

相关推荐