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

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

    Go with the assumption that the two lists are sorted before entering your sharedStr algorithm. You'd want to keep two references: each to an element in each of the two lists.

    Then you'd start comparing element after element and progress either or both of the references accordingly. Here's a pseudo-code:

    def sharedStr(lista, listb):
        indexa = indexb = 0
        shared = 0
    
        while 1:
            try:
                a = lista[indexa]
                b = listb[indexb]
            except IndexError:     # we fell off one of the lists
                break
    
            if a == b:
                shared += 1
                indexa += 1
                indexb += 1
            elif a < b:
                indexa += 1
            else:    # b < a
                indexb += 1
    
        return shared
    

    Yes, this is also a valid Python code. ;-)

提交回复
热议问题