设计公司vi天津百度快照优化公司
别问我为什么今天做了两题,问就是我干概率论干废了,需要换换脑子想想不同类型的问题,所以来刷刷算法
一、题目
二、解题思路
1、我的思路
其实这题思路还挺简单的,我直接把代码放这,大家应该稍微看看就能懂
char[] ch = haystack.toCharArray();char[] cn = needle.toCharArray();for (int i = 0; i < ch.length; i++) {if(ch[i] == cn[0]){int flag = 1;for(int j=1;j<cn.length;j++){if(i+j > ch.length - 1 || ch[i+j] != cn[j]){flag = 0;break;}}if(flag == 1){return i;}}}return -1;
值得注意的是,需要考虑到下图出现的特殊情况,我一开始就没考虑
2、官方题解
方法一:暴力匹配
这种算法思路和我的思路是一样的,只是我的flag用的是int类型,题解中用的是boolean类型,这是之前刷C语言留下来的后遗症……可恶,我以后也要养成习惯用boolean类型
class Solution {public int strStr(String haystack, String needle) {int n = haystack.length(), m = needle.length();for (int i = 0; i + m <= n; i++) {boolean flag = true;for (int j = 0; j < m; j++) {if (haystack.charAt(i + j) != needle.charAt(j)) {flag = false;break;}}if (flag) {return i;}}return -1;}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:Knuth-Morris-Pratt算法
一个我听都没听过的算法,这种方法在力扣上的说明文字非常非常长,我我我偷个懒就直接放代码了,嘻嘻
class Solution {public int strStr(String haystack, String needle) {int n = haystack.length(), m = needle.length();if (m == 0) {return 0;}int[] pi = new int[m];for (int i = 1, j = 0; i < m; i++) {while (j > 0 && needle.charAt(i) != needle.charAt(j)) {j = pi[j - 1];}if (needle.charAt(i) == needle.charAt(j)) {j++;}pi[i] = j;}for (int i = 0, j = 0; i < n; i++) {while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {j = pi[j - 1];}if (haystack.charAt(i) == needle.charAt(j)) {j++;}if (j == m) {return i - m + 1;}}return -1;}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。