给出一个字符串,说s="##$$$#"
,如何找到索引前的“#”符号数量等于索引后的“ $”符号数量的索引?
示例:如果为s="##$$$#"
,则输出为2。
说明:索引2之前有2个“#”符号,索引2之后有2个“ $”符号
我尝试先找到中间索引并计算两侧的符号(#和$),如果它们相等,则打印中间索引,否则增加中间数并以相同的方式进行。 但是我无法正确理解逻辑。
答案 0 :(得分:0)
一种方法是:
At any given index 'i' ,
Count_Pound[i] = Count_Pound[i-1] + 1 if charAt(i-1) is '#'
= Count_Pound[i-1] if charAt(i-1) is '$'
E.g. Count_Pound[0] = 0;
Count_Pound[1] = 0 + 1 if charAt(0) = '#'
= 0 if charAt(0) is '$'
类似的方法适用于反向移动。
Count_Dollar[j] = Count_Dollar[j+1] + 1 if charAt(j+1) is '$'
= Count_Dollar[j+1] if charAt(j+1) is '#'
E.g. Count_Dollar[str.length -1] = 0
Count_Dollar[str.length - 2] = 0 + 1 if charAt(str.length-1) is '$'
= 0 if charAt(str.length-1) is '#'
在遍历正向和反向方式后有了这两个数组-顺便说一句,您可以仅在一个循环中构建这两个数组,并具有两个索引,一个递增和一个递减。然后遍历这些数组并获得最大的数组(我假设您想要最大的数组)。
for i : 0 to str.length-1:
if Count_Pound[i] == Count_Dollar[i] && max_value < Count_Pound[i]
max_value = Count_Pound[i]
ans = i
return ans
空间复杂度不错:O(n),时间复杂度不错:O(n)
答案 1 :(得分:0)
您可以尝试使用for循环来测试字符串中的每个位置吗?据我所知,似乎当您说索引2是答案时,索引本身就被排除在外了,所以您得到str[:index]
到str[index+1:]
所以你会得到这样的东西:
def half(str, first_half, second_half):
for i in range(len(str)):
if str[:i].count(first_half) == str[i+1:].count(second_half):
return i
return None
答案 2 :(得分:0)
这应该缩放为O(N):
def same_count(s):
c1 = 0
c2 = 0
l1 = list()
l2 = list()
n = len(s)
for i in range(n):
# count forward from start
if s[i] == '#':
c1 += 1
# count backward from end
if s[n - i - 1] == '$':
c2 += 1
l1.append(c1)
l2.append(c2)
# reverse second list
l2 = list(reversed(l2))
# find index where counts are the same
match = [i for i in range(1,n-1) if
l1[i-1] == l2[i+1]]
if match:
return match[0]
else:
return None
print(same_count('##$$$#'))
print(same_count('###$$$##'))
print(same_count('#$$'))
#output:
#2
#None
#1
答案 3 :(得分:0)
string = '##$$$#'
foundHash = False
foundDollar = False
dollarIndex = -1
hashCount = 0
dollarCount = 0
for i,c in enumerate(string):
if c == '#' and not foundHash:
hashCount = hashCount + 1
foundHash = True
elif c == '#' and foundHash and not foundDollar:
hashCount = hashCount + 1
elif c == '$' and foundHash and not foundDollar:
dollarIndex = i
foundDollar = True
elif c == '$' and foundHash and foundDollar:
dollarCount = dollarCount + 1
else:
if hashCount == dollarCount:
break
else:
foundHash = False
foundDollar = False
dollarIndex = -1
hashCount = 0
dollarCount = 0
if c == '#' and not foundHash:
hashCount = hashCount + 1
foundHash = True
if dollarIndex > 0 and hashCount == dollarCount:
print("index = %d" %(dollarIndex))
else:
print("index not found")