Which are in?

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;
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,400评论 0 23
  • 16岁,我们在做什么? 这是正当好的年龄,享受着青春的阳光气息,不必担忧未来,因为有大把的时光值得我们去挥霍,让我...
    念念云耳阅读 136,915评论 10 116
  • 170331@D86.感恩冥想 佩诗 。深深的感恩慈悲伟大的佛陀,感谢感谢感谢! 。感恩格西老师用现代化的语言教授...
    佩诗阅读 1,280评论 0 0
  • 清晨的风从南方吹来,空气清冷干燥。 当竹子小姐早早起来吃过早餐,外出一趟后,我还在深深的睡梦中。 她捣...
    三水林枫阅读 1,644评论 0 0
  • 大学教会我们的不是如何治病救人,是如何看待生命
    田佳星阅读 721评论 0 0