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

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

    int x =  0;
    int i= 0;
    int j = 0;
    while(i != list1.length && j != list2.length){
      int v = list1[i].compareTo(list2[j]);
      if (v == 0){
        x++;i++;j++;
      }else if (v < 0){
        i++;
      } else {
        j++;
      }
    }
    return x;
    

    This makes the straightforward assumption that the strings are sorted using String.compareTo which would make sense.

提交回复
热议问题