给定两个字符串数组,a和b,每个字符串按字母顺序排列,我想返回两个数组中匹配的字符串数量的计数。
public int countMatch(String[] a, String[] b) {
}我的目标是能够按以下方式调用该方法;
countMatch({"apple", "banana", "xylophone"}, {"banana", "carrot", "dog", "xray", "xylophone"});它应该返回int值2,因为有两个字符串匹配每个数组(“香蕉”和“木琴”)。
需要注意的是,如果这有助于解决问题,则数组将始终按字母顺序排列。
发布于 2015-03-27 04:54:41
我的代码如下:
public class Test {
public static int findMatchCount(final String [] a,final String [] b){
int matchCount = 0;
for(int i = 0, j = 0;i < a.length && j < b.length;){
int res = a[i].compareTo(b[j]);
if(res == 0){
matchCount++;
i++;
j++;
}else if(res < 0){
i++;
}else{
j++;
}
}
return matchCount;
}
public static void main(String[] args){
String[] a = {"apple", "apple"};
String[] b = {"apple", "apple"};
System.out.println(findMatchCount(a,b));
}
}发布于 2015-03-27 04:19:01
一旦对这些数组进行了排序,您就可以这样做:
您将有两个变量:i和j。第一个将遍历第一个数组,第二个将遍历第二个数组。
然后比较a[i]和b[j]。如果它们相等,则是匹配的,并且您将两个索引都提前。如果它们不是相等的,则前进指数在word处较小(如果a[i] < b[j]前进,则为i j)。
发布于 2015-03-27 04:37:35
您可以创建一个简单的方法,如:
public int countMatch(String[] a, String[] b) {
List<String> list1 = new ArrayList(Arrays.asList(a));
List<String> list2 = Arrays.asList(b);
list1.retainAll(list2);
return list1.size();
}https://stackoverflow.com/questions/29293173
复制相似问题