Problem:
Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length, including 0.
matchUp({"aa", "bb", "cc"}, {"aaa", "xx", "bb"}) → 1
matchUp({"aa", "bb", "cc"}, {"aaa", "b", "bb"}) → 2
matchUp({"aa", "bb", "cc"}, {"", "", "ccc"}) → 1
Solution:
public int matchUp(String[] a, String[] b) { int count = 0; for (int i = 0; i < a.length; i++) { String tmp1 = a[i]; String tmp2 = b[i]; if (!tmp1.equals("") && !tmp2.equals("")) { if (tmp1.charAt(0) == tmp2.charAt(0)) count++; } } return count; }
String tmp1 = a[i];
ReplyDeleteString tmp2 = b[i];
These string variables should be declared outside the for loop. Declare once, use over and over again.
int count = 0;
ReplyDeletefor(int i=0; i<a.length; i++){
if(!b[i].isEmpty() && !a[i].isEmpty() && a[i].substring(0, 1).equals(b[i].substring(0, 1))) count++;
}
return count;
public int matchUp(String[] a, String[] b) {
ReplyDeleteint c = 0;
for(int i = 0; i < a.length; i++){
if(a[i].length() == 0 || b[i].length() == 0){
continue;
}
if(a[i].charAt(0) == b[i].charAt(0)){
c++;
}
}
return c;
}
hopefully more understandable.
With Java Stream
ReplyDeletepublic int matchUp(String[] a, String[] b) {
return (int)java.util.stream.IntStream.range(0, a.length)
.filter(i -> !a[i].equals("") && !b[i].equals(""))
.filter(i -> a[i].charAt(0) == b[i].charAt(0))
.count();
}