美文网首页
Which are in?

Which are in?

作者: Magicach | 来源:发表于2017-12-28 13:22 被阅读0次

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

Example 1: a1 = ["arp", "live", "strong"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

Example 2: a1 = ["tarp", "mice", "bull"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []
Notes:

Arrays are written in "general" notation. See "Your Test Cases" for examples in your language.

In Shell bash a1 and a2 are strings. The return is a string where words are separated by commas.

Beware: r must be without duplicates.

Good Solution1:

import java.util.Arrays;

public class WhichAreIn { 
    
  public static String[] inArray(String[] array1, String[] array2) {
    return Arrays.stream(array1)
      .filter(str ->
        Arrays.stream(array2).anyMatch(s -> s.contains(str)))
      .distinct()
      .sorted()
      .toArray(String[]::new);
  }
}

Good Solution2:

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;

public class WhichAreIn { 
  
  public static String[] inArray(String[] array1, String[] array2) {
     Set<String> result = new HashSet<>();
     
     for(String a1 : array1) {
       for(String a2 : array2) {
         if(a2.contains(a1)) {
           result.add(a1);
           break;
         }
       }
     }
     
     String[] resultArray = result.toArray(new String[result.size()]);
     
     Arrays.sort(resultArray);
     
     return resultArray;
  }
}

相关文章

  • in which, of which, at which, to

    Prepositions are words that indicate the relationships be...

  • which

  • Which are in?

    Given two arrays of strings a1 and a2 return a sorted arr...

  • Which

    我们已经学过如何用 which 来提问。​ ​Which team has more fans?​哪个队有更多球迷...

  • 无标题文章

    which 命令 which node : 查看node的安装路径 which babel \ which web...

  • which从句

    介词 + which 引导定语从句 名词 , which which 引导定语从句

  • Mac常用终端命令总结

    参考1、which [命令名词] #显示系统命令所在目录。如,which node、which npm、which...

  • Which one?

    “相互独立又相互依赖的 才是爱” ​​​ ​​​​

  • “that” 还是“which”

    “which”如果使用不当可引起歧义。它常与“that”混用。“that”和“which”都引导定语从句,但“th...

  • Which Means

    Writing is something by nature I want to write is totally...

网友评论

      本文标题:Which are in?

      本文链接:https://www.haomeiwen.com/subject/jbamgxtx.html