Advertisement
scottashipp

Solution for has reverse twice

Feb 11th, 2014
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1.        /**
  2.      * Solution for the has reverse twice problem: Given two arrays, a1 and a2, determine if the reverse of a2 is found inside a1 twice.
  3.      * @param a1 an array of integers to search within
  4.      * @param a2 search a1 for two matches to the reverse of a2
  5.      * @return true if a2's reverse occurs twice in array a1
  6.      */
  7.     public static boolean hasReverseTwice(int[] a1, int[] a2) {
  8.         //guard against checking bad data
  9.         if(a1 == null || a2 == null || a2.length == 0) {
  10.             return false;
  11.         }
  12.        
  13.         //track the number of ints within array a2 that have matched a1 as we go
  14.         int a2MatchCount = 0;
  15.         //track the number of total matches as we go
  16.         int matches = 0;
  17.        
  18.         //do the work
  19.         for(int i = 0; i < a1.length - a2.length + 1; i++) {
  20.             a2MatchCount = (a1[i] == a2[a2.length - 1 - a2MatchCount]) ? a2MatchCount + 1 : 0;
  21.             if(a2MatchCount == a2.length) {
  22.                 matches++;
  23.                 a2MatchCount = 0;
  24.             }
  25.         }
  26.        
  27.         //return true if there were two matches
  28.         return matches == 2;
  29.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement