我做了采访街头问题string similarity。最初我在python中做了这个。这给了我最后5个测试用例的Time Limit Exceeded错误。然后我在java中尝试了相同的方法,并且解决方案得到了接受。前5个测试用例的java和python版本之间的时间差异非常高,但对于前5个测试用例,python比较了java。为什么?为什么同样算法的运行时差异很大?
字符串的长度可以去高达100000
stringsim.py
N=int(raw_input())
while N!=0:
rootstr=[i for i in raw_input()]
solution=0
for i in xrange(len(rootstr)):
for j in xrange(i,len(rootstr)):
if(rootstr[j-i]==rootstr[j]):solution+=1
else:break
print solution
N-=1
Solution.java:
class Solution{
public static void main(String[] args) {
java.util.Scanner sc=new java.util.Scanner(System.in);
int N=sc.nextInt(),sol;
while(N--!=0){
sol=0;
char[] s=sc.next().toCharArray();
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length;j++){
if(s[j]==s[j-i]) sol++;
else break;
}
}
System.out.println(sol);
}
}
}
Run time for java: 1 Success 0.172387 2 Success 0.172177 3 Success 0.172185 4 Success 0.172178 5 Success 0.263904 6 Success 2.82661 7 Success 4.66869 8 Success 4.83201 9 Success 1.36585 10 Success 1.02123 For python: 1 Success 0.081229 2 Success 0.081047 3 Success 0.081032 4 Success 0.081015 5 Success 0.910672 6 Time limit exceeded. 16.1818 7 Time limit exceeded. 16.2357 8 Time limit exceeded. 16.2001 9 Time limit exceeded. 16.2408 10 Time limit exceeded. 16.1831
而且错误 - 这段代码提供的“解决方案”的**含义究竟是什么? –
可能是JIT – nullpotent
为了提高您获得深刻见解的答案的机会,请发布一个链接到输入文件,并将您的数字时间度量值作为表格发布,突出显示哪些单元格令人惊讶。没有这些数据,你的具体问题很难回答。 – pts