标签:length ica can tco div boolean while pattern ret
class Solution { public int strStr(String haystack, String needle) { if (haystack.length() < needle.length()) { return -1; } if (needle.length() == 0) { return 0; } char[] toMatch = haystack.toCharArray(); char[] pattern = needle.toCharArray(); for (int i = 0; i < toMatch.length - pattern.length + 1; i++) { if (toMatch[i] == pattern[0] && isMatch(toMatch, i, pattern, 0)) { return i; } } return -1; } private boolean isMatch(char[] a, int i1, char[] b, int i2) { while (i1 < a.length && i2 < b.length && a[i1] == b[i2]) { i1++; i2++; } return i2 == b.length; } }
We can avoid more duplicate work by check [0, haystack - needle + 1] length.
Need to revisit KMP
标签:length ica can tco div boolean while pattern ret
原文地址:http://www.cnblogs.com/shuashuashua/p/7452890.html