GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/src/StrStr.java at master · LeBW/leetcode Expand file tree/ Copy pathStrStr.javaMore file actions 66 lines (64 loc) · 1.69 KB / Copy pathStrStr.javaFile metadata and controls66 lines (64 loc) · 1.69 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 /** * <a href=https://leetcode-cn.com/problems/implement-strstr/description/> * Click to see online description * </a> * <br> * Implement KMP algorithm. * @author LBW */ public class StrStr { public int strStr(String haystack, String needle) { if (needle.equals("")) return 0; // get the array {next}. int[] next = getNext(needle); // start to traverse the string by i. (j is used to indicate index of needle) int i = 0, j = 0; while (i < haystack.length()) { if (haystack.charAt(i) == needle.charAt(j)) { i++; j++; } else if (j > 0) { j = next[j-1]; } else { // j = 0 i++; } if (j == needle.length()) { return i - needle.length(); } } return -1; } /** * Get next array. * @param needle * @return next */ private int[] getNext(String needle) { int len = needle.length(); int[] next = new int[len]; next[0] = 0; int i = 1, j = 0; while (i < len) { if (needle.charAt(i) == needle.charAt(j)) { next[i] = j + 1; i++; j++; } else if (j == 0) { next[i] = 0; i++; } else { // j > 0 j = next[j-1]; // This step is really important! j indicates candidates of next. } } return next; } public static void main(String[] args) { StrStr strStr = new StrStr(); strStr.strStr("hello", "ll"); } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |