Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package System;
- import java.util.ArrayList;
- public class Search {
- private int[] bad_shift; //Jeg finner ikke et bedre navn. Koperte dette fra timen.
- private final int CHAR_MAX = 256;
- public Search() {
- bad_shift = new int[CHAR_MAX];
- }
- public int[] find(char[] needle, char[] haystack){
- ArrayList<Integer> list = new ArrayList<>();
- if (needle.length>haystack.length) return null;
- if (needle.length == 0) return new int[0];
- for (int i = 0; i < bad_shift.length; i++) {
- bad_shift[i] = needle.length;
- }
- int offset = 0, needleScan = 0;
- int maxOffset = haystack.length - needle.length;
- int end = needle.length-1;
- for (int i = 0; i < end; i++) {
- bad_shift[(int)needle[i]] = end - i;
- }
- while(offset < maxOffset){
- //The needleScan start at the end and check backwards until it hits a mismatch. Since _ should allow any kind of symbol
- //then we can simply skip once if we find this char in the current needle char.
- for(needleScan = end; needle[needleScan] == haystack[needleScan+offset] || needle[needleScan] == '_'; needleScan--){
- if(needleScan == 0){ // this will count down for every match until 0. Then we have found the needle.
- list.add(new Integer(offset));
- break;
- }
- }
- offset += bad_shift[haystack[offset + end]];
- }
- Integer[] temp = list.toArray(new Integer[list.size()]);
- int[] results = new int[temp.length];
- for (int i = 0; i < results.length; i++) {
- results[i] = temp[i].intValue();
- }
- return results;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment