拆分字符串后ArrayIndexOutOfBoundSexception
尝试将此代码提交给hackerrank时,我会遇到以下错误.com/挑战/联系人/问题:
线程中的异常“ main” java.lang.arayindexoutofboundsexception:1 结果.contacts(solution.java:31) 在solution.main(解决方案
,它似乎在我的本地机器上工作,但是我不确定在拆分单词后是否存在问题。当我通过调试检查时,它似乎是正确的,但是我不确定在拆分后是否需要使用额外的支票。否则可能会有一个问题。
public static void main(String[] args) {
List<String> s = List.of("add hack", "add hackerrank", "find hac", "find hak");
List<List<String>> queries = Collections.singletonList(s);
List<Integer> result = contacts(queries);
result.forEach(System.out::println);
}
public static List<Integer> contacts(List<List<String>> queries) {
Set<String> set = new HashSet<>();
List<Integer> result = new ArrayList<>();
for (List<String> query : queries) {
for (String s : query) {
// !!! the problem may be caused from these lines >>>
String operation = s.split(" ")[0];
String word = s.split(" ")[1];
if (operation.equals("add")) {
set.add(word);
} else if (operation.equals("find")) {
long count = set.stream().filter(c -> c.startsWith(word)).count();
result.add((int) count);
}
}
}
return result;
}
那么,问题的原因可能是什么?
I am getting the following error when trying to submit this code to hackerrank on https://www.hackerrank.com/challenges/contacts/problem:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Result.contacts(Solution.java:31)
at Solution.main(Solution.java:66)
However, it seems to work on my local machine, but I am not sure if there is a problem after splitting the words. It seems to be split properly as I check by debugging, but I am not sure if I need to use an extra check after split. Or there may be a problem for split.
public static void main(String[] args) {
List<String> s = List.of("add hack", "add hackerrank", "find hac", "find hak");
List<List<String>> queries = Collections.singletonList(s);
List<Integer> result = contacts(queries);
result.forEach(System.out::println);
}
public static List<Integer> contacts(List<List<String>> queries) {
Set<String> set = new HashSet<>();
List<Integer> result = new ArrayList<>();
for (List<String> query : queries) {
for (String s : query) {
// !!! the problem may be caused from these lines >>>
String operation = s.split(" ")[0];
String word = s.split(" ")[1];
if (operation.equals("add")) {
set.add(word);
} else if (operation.equals("find")) {
long count = set.stream().filter(c -> c.startsWith(word)).count();
result.add((int) count);
}
}
}
return result;
}
So, what may the cause of the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是您如何解释“查询”是什么。 操作和 word 不在单个字符串中。它们是查询中的元素。因此...
这是针对那些不先尝试自己的建议就喜欢发表评论的人。
Your problem is how you interpreted what "query" is. Operation and Word are not in a single String. they are elements in the query. Therefore...
This is for people who love to comment without trying their own suggestions first.