约束:
0<T<100
0<N<10000
输入:
2
6
abcdef
3
abc
输出:
bdfeca
bca
我花了很多时间试图解决这个问题,并且受够了我遇到的错误,
我知道 C、C++ 更快,因为它们只使用编译器,与 Java、Python 相比,因为它们也使用解释器,
但是我的代码在 Python2 和 Python3 上做得很好,
他们还有比这更能降低时间复杂度的其他逻辑吗,
我想我已经在 O(n) 时间复杂度内完成了。
我的 Java 代码:(我的代码超出时间限制的地方)
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int t = Integer.parseInt(sc.nextLine()), i;
while ( t --> 0 )
{
int n = Integer.parseInt(sc.nextLine());
String a = sc.nextLine();
for(i=1;i<n;i+=2)
System.out.print(a.charAt(i));
i=n-1;
if(n%2==0)
i--;
for(;i>=0;i-=2)
System.out.print(a.charAt(i));
System.out.println();
}
}
}
我的 C 代码:
#include <stdio.h>
int main()
{
int t, n, i;
char a[10000];
scanf("%d",&t);
while(t--)
{
scanf("%d %s",&n,a);
for(i=1;i<n;i+=2)
printf("%c",a[i]);
i=n-1;
if(!(n&1))
i--;
for(;i>=0;i-=2)
printf("%c",a[i]);
printf("\n");
}
return 0;
}
我在 Python3 中的代码:
from __future__ import print_function
t = int(input())
for i in range(t):
n=int(input())
a=input()
for i in range(1,n,2):
print(a[i],end='')
i=n-1
if(n%2==0):
i=i-1
for q in range(i,-1,-2):
print(a[q],end='')
print("\n")
限制:
时间限制:每个输入文件 0.15 秒。
内存限制:256 MB
源限制:1024 KB
最佳答案
我发现我的 Java 代码变慢了,
即,在 System.out.println(a.charAt(i))
,
所以为了最小化它,我们使用 StringBuilders 并更新它,然后最终在 final 打印
由此我们可以说 public char charAt(int index)
方法比 public String substring(int beginIndex, int endingIndex)
(one构造函数)
所以,我满足所有条件的最终 Java 代码(与以前相比花费的时间更少)是:
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int t = Integer.parseInt(sc.nextLine()), i;
while(t-->0)
{
int n = Integer.parseInt(sc.nextLine());
StringBuilder str = new StringBuilder("");
String a = sc.nextLine();
for(i=1;i<n;i+=2)
str.append(a.substring(i,i+1));
i=n-1;
if(n%2==0)
i--;
for(;i>=0;i-=2)
str.append(a.substring(i,i+1));
System.out.println(str);
}
}
}
关于java - 我的 Java 代码超出了 TimeLimit,而 C/C++/Python/Python3 中的相同逻辑正在被更大的测试用例接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42785993/