Suppose I am given a string of len n, for every substring whose first and last characters are same I should add 1 to fx and print the final fx.
ex for "ababaca" , f("a")=1 , f("aba")=1 , f("abaca")=1, but f("ab")=0
n = int(raw_input())
string = list(raw_input())
f = 0
for i in range(n):
for j in range(n,i,-1):
temp = string[i:j]
if temp[0]==temp[-1]:
f+=1
print f
Is there any way I can optimize my code for large strings as I am getting time out for many test cases.