在Java中对字符串进行排序并提取两个String数组的公共元素 [英] Sorting Strings and extracting common elements of two String arrays in Java

查看:332
本文介绍了在Java中对字符串进行排序并提取两个String数组的公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求写下一个Java函数sharedStr,该函数通过给定2个String s的排序数组,返回出现在两个数组中的String s的数量.

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

此代码的解决方案必须是线性的,这意味着我必须仅对每个数组进行一次遍历.否则,我可以将第一个数组中的每个String与另一个数组中的所有String进行比较.

The solution for this code must be linear, which means that I must go through each array only once. Otherwise, I could just compare each String in the first array to all the Strings in the other array.

例如以下对sharedStr

sharedStr({"Call","me","Ishmael"},{"Call","me","Jonha"});

必须返回2.我希望您的帮助来理解包含 String s 的排序数组是什么意思?数组的排序方式没有任何特殊说明. String s的基本普通排序是什么?

must return 2. I would like your help to understand what does it mean sorted arrays that contain Strings? There isn't any special description of the way the arrays have been sorted. What is the basic ordinary sorting of Strings?

一个人如何在两个String之间进行比较?如果尝试这样做,则会出现编译器错误. (我正在使用Eclipse.我注意到char可以自动比较).

How does one compare between two Strings anyway? If I try to do so, I get a compiler error. (I'm using Eclipse. I noticed that chars can be compared automatically).

推荐答案

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;

这是一个简单的假设,即使用String.compareTo对字符串进行排序,这很有意义.

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

这篇关于在Java中对字符串进行排序并提取两个String数组的公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆