繁体   English   中英

拆分字符串后出现 ArrayIndexOutOfBoundsException

[英]ArrayIndexOutOfBoundsException after splitting a string

尝试将此代码提交到https://www.hackerrank.com/challenges/contacts/problem上的 hackerrank 时出现以下错误:

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:1 在 Result.contacts(Solution.java:31)在 Solution.main(Solution.java:66)

不过在我本地机器上好像可以,但是我不确定分词后会不会有问题。 当我通过调试检查时,它似乎被正确地分割了,但我不确定分割后是否需要使用额外的检查。 或者拆分可能有问题。

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;
}

那么,问题的原因可能是什么?

您的问题是您如何解释“查询”是什么。 OperationWord不在一个 String 中。 它们是查询中的元素。 所以...

for (List<String> query : queries) {
    String operation = query.get(0);
    String word = query.get(1);
    // The rest of your code;
}

在此处输入图像描述

这是为那些喜欢发表评论而不先尝试自己的建议的人准备的。 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM