Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Solution for the has reverse twice problem: Given two arrays, a1 and a2, determine if the reverse of a2 is found inside a1 twice.
- * @param a1 an array of integers to search within
- * @param a2 search a1 for two matches to the reverse of a2
- * @return true if a2's reverse occurs twice in array a1
- */
- public static boolean hasReverseTwice(int[] a1, int[] a2) {
- //guard against checking bad data
- if(a1 == null || a2 == null || a2.length == 0) {
- return false;
- }
- //track the number of ints within array a2 that have matched a1 as we go
- int a2MatchCount = 0;
- //track the number of total matches as we go
- int matches = 0;
- //do the work
- for(int i = 0; i < a1.length - a2.length + 1; i++) {
- a2MatchCount = (a1[i] == a2[a2.length - 1 - a2MatchCount]) ? a2MatchCount + 1 : 0;
- if(a2MatchCount == a2.length) {
- matches++;
- a2MatchCount = 0;
- }
- }
- //return true if there were two matches
- return matches == 2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement