Sorting Strings and extracting common elements of two String arrays in Java

前端 未结 8 1028
南方客
南方客 2020-12-22 12:01

I was asked to write down a Java function sharedStr that by given 2 sorted arrays of Strings, returns the number of Strings that appea

8条回答
  •  有刺的猬
    2020-12-22 12:17

    The fact that the arrays are sorted is a red herring, it is irrelevant to the solution. Use a Map Steps:

    1. For each string in the first array do the following:
      1. do a map.get(currentString)
      2. if that is null, do a map.put(currentString, new Integer(0))
    2. For each string in the second array do the following:
      1. do a map.get(currentString)
      2. if that is null, ignore it, it is not a duplicate.
      3. If that is not null, do a map.put(currentString, new Integer(currentInteger.intValue() + 1);
    3. do a map.getKeySet().iterator() and iterate through the keys.
    4. for each key, get the value. The value is the count of strings that are in both arrays.

提交回复
热议问题