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

前端 未结 8 1110
南方客
南方客 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:29

    First, the second part of your question:

    Comparing strings in Java isn't as simple as:

    if(sStringOne == sStringTwo)
        //Equal
    

    you should instead use methods of the string class

    if(sStringOne.equals(sStringTwo)
        // Equal
    

    Second, the first part of your question:

    Yes, it would be easy to loop through the first array and count each indexs occurence in the second array. Since you've specified each array must be iterated only once however, perhaps the following algorithm may suit:

    1. Create an integer variable initialised to zero to count the matching occurences.
    2. Loop through array one 2.1 For each index, check to see if it's string is present in the other array, do this with the contains function contains function example 2.2 If string is found in other array, increment counter.
    3. read the counter, this is the number of matching strings

提交回复
热议问题