Advertisement
redwoolwinterhat

CodingBat Java > AP-1 > commonTwo

Jun 19th, 2013
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. public int commonTwo(String[] a, String[] b) {
  2.   int indA = 0;
  3.   int indB = 0;
  4.   int count = 0;
  5.   int temp = 0;
  6.   String str = "";
  7.  
  8.   while(indA<a.length && indB<b.length) {
  9.  
  10.     //Skips letters previously matched
  11.     while(str.contains(a[indA]) && indA<a.length-1) indA++;
  12.     while(str.contains(b[indB]) && indB<b.length-1) indB++;  //etc.
  13.    
  14.     // Helps test matches & decide which array position to increment
  15.     temp = a[indA].compareTo(b[indB]);  
  16.    
  17.     // If there is a match, increment both arrays,
  18.     //count and add the matched letter to str
  19.     if ( temp==0 ) {
  20.       count++;
  21.       str += a[indA];
  22.       indA++;
  23.       indB++;
  24.     }
  25.     if (temp<0) {  // If a is before b, increment array A.
  26.       indA++;
  27.     }
  28.     if (temp>0) {  // If b is before a, increment array B.
  29.       indB++;
  30.     }
  31.   }
  32.   return count;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement