简体   繁体   English

检索以数组中的字符串为前缀的字符串

[英]Retrieve strings prefixed by a string in an array

Write a Java code of the method that takes an array of strings and a String (S(. The method should return an integer that is the number of strings that starts with S.编写该方法的 Java 代码,该方法接受一个字符串数组和一个字符串 (S(。该方法应返回一个整数,即以 S 开头的字符串的数量。

For example if: array_words = { "All", "Arab", "size", "Almond", "Allowed", "here"} and S= "All", then the method should return 2例如,如果:array_words = { "All", "Arab", "size", "Almond", "Allowed", "here"} 和 S="All",则该方法应返回 2

what is the idea of searching here ?在这里搜索的想法是什么?

The best, fastest and cheapest solution, for a larger input though, is to store all words of the array into a DWAG .对于更大的输入,最好、最快和最便宜的解决方案是将数组的所有单词存储到DWAG 中

That would bring the memory requirements to almost optimal for storing all words and would give a search time complexity of O(m) (m being the size of S).这将使存储所有单词的内存需求几乎达到最佳状态,并且搜索时间复杂度为 O(m)(m 是 S 的大小)。

A slightly less memory optimal structure would be a trie .稍微少一点的内存优化结构将是一个trie

Some people ask homework questions sometimes on SOF, and sometimes they get answers a little out of scope.有些人有时会在 SOF 上提出家庭作业问题,有时他们得到的答案有点超出范围。

Loop through the array and use the startsWith method.循环遍历数组并使用startsWith方法。

I know you can take it up from here.我知道你可以从这里开始。

Iterate over the array and check if each element in the array starts with string S. If it does, increment the count variable.遍历数组并检查数组中的每个元素是否以字符串 S 开头。如果是,则增加计数变量。

Return the count variable after iterating over the array.遍历数组后返回计数变量。

public class stack {
    public static void main(String[] args) {

        String[] arr = { "All", "Arab", "size", "Almond", "Allowed", "here"};
        String S = "All";
        System.out.println(numberOfOccurrences(S, arr));

    }

    public static int numberOfOccurrences(String S, String[] array_words) {

        int count = 0;
        for (String stringElement : array_words) {
            if (stringElement.startsWith(S)) {
                count++;
            }
        }

        return count;
    }
}

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

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