网站开发制作费入会计科目市场监督管理局
题解一
思路
双层循环暴力解,只要needle的第一位和haystack的某一位对应,就进入内循环,如果超限或者某一位不同,跳出内循环,继续寻找下一个和needle第一位匹配的字符。
代码
class Solution {public int strStr(String haystack, String needle) {for(int i = 0; i < haystack.length(); i++){if(haystack.charAt(i) == needle.charAt(0)){for(int j = 0; j < needle.length(); j++){if(i + j > haystack.length() - 1 || haystack.charAt(i + j) != needle.charAt(j)) break;if(j == needle.length() - 1) return i;}}}return -1;}
}
总结
时间复杂度O(mn),空间复杂福挺简单的,没啥要总结的。
题解二
思路
据说这个题是KMP算法的经典应用场景。
代码
class Solution {public int strStr(String haystack, String needle) {int[] next = new int[needle.length()];getNext(next, needle);int j = 0;for(int i = 0; i < haystack.length(); i++){while(j > 0 && haystack.charAt(i) != needle.charAt(j)){j = next[j - 1];} if (haystack.charAt(i) == needle.charAt(j)) j++;if (j == needle.length()) return i - needle.length() + 1;}return -1;}public void getNext(int[] next, String s){next[0] = 0;int j = 0;for(int i = 1; i < s.length(); i++){while(j > 0 && s.charAt(i) != s.charAt(j)){j = next[j - 1];}if (s.charAt(i) == s.charAt(j)){j++;}next[i] = j;} }
}
总结
时间复杂度O(m+n),KMP算法太强了,有时间我一定要专门开个帖子讲讲我对KMP的理解。(开个超级大坑)
KMP简直太神了,巧夺天工。
ps:第一次知道if后面还要+空格(标准化)。