使用 java 比较字符串的替代字符的最快方法是什么?
What is the fastest way to compare alternate characters of a string using java?
有多个字符串从标准输入传递到此程序。第一个 int 输入 T,是传递给该程序的测试用例(字符串)的数量。具有不同替代字符的字符串是完美的。如果替代字符相同,则需要删除这两个字符中的一个。基本上,你要数一数,你需要删除多少个字符才能得到一个完美的String?例如:ABABAB 是完美的,而 AABABAA 是不完美的。你需要删除2个A,第一个和最后一个one.InAAAA,你需要删除3个A才能得到一个完美的字符串。字符串输入可能非常大。计算此类删除次数的最快方法是什么?以下代码由我编写,运行速度非常慢。
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int T= scan.nextInt();
String str;
int count=0;
for(int i=0; i<T; i++){
str=scan.next();
for(int j=0; j<str.length()-1; j++){
if(str.charAt(j)!=str.charAt(j+1)){
j+=2;
}
else{
count++;
}
}
System.out.println(count);
}
}
在担心性能之前,请先担心您的解决方案是否正确。对于输入ABAAB,你的程序returns0,但是1要去掉A才能得到完美的字符串
然后:"very large" 是什么意思?那是多少个字符?什么是 "very slow"?
您将不得不至少查看字符串中的每个字符一次,因此您不会变得更快。但是,您可以稍微优化一下。目前,您可能会查看单个字符 两次 (一次在 str.charAt(j+1)
中,下一次在 str.charAt(j)
中)。当然可以将您的算法编写为字符串的每个字符都被访问恰好一次。但同样,在关注速度之前,您应该关注正确性。
这是我排除所有逻辑错误后的工作代码。对于某些测试用例,其执行时间长达 0.45-0.50 秒。它的性能可以提高吗?
public static void main(String[] args) {
int T=0; String str;
Scanner sc = new Scanner(System.in);
T=sc.nextInt();
for(int i=0; i<T; i++){
str= sc.next();
solve(str);
}
}
public static void solve(String str){
char first, second; int count=0;
for(int i=0; i<str.length()-1; i++){
first= str.charAt(i);
second= str.charAt(i+1);
if(first==second){
count++;
}
}
System.out.println(count);
}
有多个字符串从标准输入传递到此程序。第一个 int 输入 T,是传递给该程序的测试用例(字符串)的数量。具有不同替代字符的字符串是完美的。如果替代字符相同,则需要删除这两个字符中的一个。基本上,你要数一数,你需要删除多少个字符才能得到一个完美的String?例如:ABABAB 是完美的,而 AABABAA 是不完美的。你需要删除2个A,第一个和最后一个one.InAAAA,你需要删除3个A才能得到一个完美的字符串。字符串输入可能非常大。计算此类删除次数的最快方法是什么?以下代码由我编写,运行速度非常慢。
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int T= scan.nextInt();
String str;
int count=0;
for(int i=0; i<T; i++){
str=scan.next();
for(int j=0; j<str.length()-1; j++){
if(str.charAt(j)!=str.charAt(j+1)){
j+=2;
}
else{
count++;
}
}
System.out.println(count);
}
}
在担心性能之前,请先担心您的解决方案是否正确。对于输入ABAAB,你的程序returns0,但是1要去掉A才能得到完美的字符串
然后:"very large" 是什么意思?那是多少个字符?什么是 "very slow"?
您将不得不至少查看字符串中的每个字符一次,因此您不会变得更快。但是,您可以稍微优化一下。目前,您可能会查看单个字符 两次 (一次在 str.charAt(j+1)
中,下一次在 str.charAt(j)
中)。当然可以将您的算法编写为字符串的每个字符都被访问恰好一次。但同样,在关注速度之前,您应该关注正确性。
这是我排除所有逻辑错误后的工作代码。对于某些测试用例,其执行时间长达 0.45-0.50 秒。它的性能可以提高吗?
public static void main(String[] args) {
int T=0; String str;
Scanner sc = new Scanner(System.in);
T=sc.nextInt();
for(int i=0; i<T; i++){
str= sc.next();
solve(str);
}
}
public static void solve(String str){
char first, second; int count=0;
for(int i=0; i<str.length()-1; i++){
first= str.charAt(i);
second= str.charAt(i+1);
if(first==second){
count++;
}
}
System.out.println(count);
}