给定一个仅由‘0’ 、 ‘1’和‘?’组成的字符串S , 任务是检查在字符‘?’ 的每个可能替换中是否存在子字符串“10” 。与1或0 。
例子:
Input: S = “1?0”
Output: Yes
Explanation:
Following are all the possible replacements of ‘?’:
- Replacing the ‘?’ with 0 modifies the string to “100”. In the modifies string, the substring “10” occurrs.
- Replacing the ‘?’ with 1 modifies the string to “110”. In the modifies string, the substring “10” occurrs.
From the above all possible replacements, the substring “10” occurs in all the replacements, therefore, print Yes.
Input: S= “??”
Output: No
方法:给定的问题可以通过使用贪心方法来解决,该方法基于观察字符串S 是否包含许多连续的“?” ,它可以替换为单个‘?’在最坏的情况下,我们可以用全1或0替换它。
因此,想法是通过替换连续的‘?’从给定的字符串S创建一个新字符串。用单个‘?’然后检查是否存在“10”或“1?0”作为子串,那么在所有可能的替换后有可能得到“10”作为子串,因此,打印Yes 。否则,打印No 。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to check it possible to get
# "10" as substring after all possible
# replacements
def check(S, n):
# Initialize empty string ans
ans = ""
c = 0
# Run loop n times
for _ in range(n):
# If char is "?", then increment
# c by 1
if S[_] == "?":
c += 1
else:
# Continuous '?' characters
if c:
ans += "?"
# Their is no consective "?"
c = 0
ans += S[_]
# "?" still left
if c:
ans += "?"
# Check if "10" or "1?0" exists
# in the string ans or not
if "10" in ans or "1?0" in ans:
return "Yes"
else:
return "No"
# Driver Code
if __name__ == '__main__':
S = "1?0"
ans = check(S, len(S))
print(ans)
输出:
Yes
时间复杂度: O(N)
辅助空间: O(N)
注意:相同的方法也可用于子字符串“00”/“01”/“11”,只需稍作改动。
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。