我已经在StackOverflow上搜索了与此错误相关的每个问题,但请相信我的情况在这里有所不同。实际上,我正在准备竞技水平的编程技能,并且在笔记本电脑上成功解决了这个问题,并且输出为100%true,对于此“黑客地球”问题(以下链接)没有任何类型的错误-
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/two-strings-4/#c198374
但是,当我尝试在黑客世界上提交我的代码时,它会引发一个错误,现在我真的很困惑,为什么在笔记本电脑上成功运行错误时会出现错误。
下面的错误屏幕截图-
这是我的代码-
import java.util.*;
class nalin{
public static void main(String args[]){
Scanner bob = new Scanner(System.in);
int bobs = bob.nextInt();
String result[] = new String[bobs];
for(int g = 0; g<bobs; g++){
Scanner s = new Scanner(System.in);
String x = s.nextLine();
String arr[] = x.split("\\s+");
int coun = 0;
char v1[] = arr[0].toCharArray();
char v2[] = arr[1].toCharArray();
for(int i = 0; i<v1.length; i++){
for(int j = 0; j<v2.length; j++){
if(v1[i] == v2[j]){
coun = coun+1;
break;
}
}
}
if(coun == v1.length){
result[g] = "YES";
}else{
result[g] = "NO";
}
}
for(int l = 0; l<result.length; l++){
System.out.println(result[l]);
}
}
}
最佳答案
注意:仅使用哈希概念。尝试以O(字符串长度)进行操作。提及本身的问题。而且您的逻辑也是错误的(检查用于字符串比较的嵌套循环。)另外,您已使扫描器降低了2倍。删除1个内部循环
您正在使用扫描仪类的nextLine方法。以下是nextline()描述
nextLine
public String nextLine()
Advances this scanner past the current line and returns the inputthat was skipped.This method returns the rest of the current line, excluding any lineseparator at the end. The position is set to the beginning of the nextline.
Since this method continues to search through the input lookingfor a line separator, it may buffer all of the input searching forthe line to skip if no line separators are present.
Returns:the line that was skipped
Throws:NoSuchElementException
1 - if no line was foundIllegalStateException
2 - if this scanner is closed.
下面是工作代码-
但是我没有纠正你的逻辑。
package Array;
import java.util.*;
class nalin {
public static void main(String args[]) {
Scanner bob = new Scanner(System.in);
int bobs = bob.nextInt();
String result[] = new String[bobs];
for (int g = 0; g < bobs; g++) {
String x = bob.next();
String y = bob.next();
//String arr[] = x.split("\\s+");
int coun = 0;
char v1[] = x.toCharArray();
char v2[] = y.toCharArray();
for (int i = 0; i < v1.length; i++) {
for (int j = 0; j < v2.length; j++) {
if (v1[i] == v2[j]) {
coun = coun + 1;
break;
}
}
}
if (coun == v1.length) {
result[g] = "YES";
} else {
result[g] = "NO";
}
}
for (int l = 0; l < result.length; l++) {
System.out.println(result[l]);
}
}
}