LeetCode028——实现strStr()

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82413774

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/implement-strstr/description/

题目描述:

知识点:

思路:遍历haystack中每一个字符,寻找可能与needle相等的字符串

遍历haystack中每一个可能与needle相同的字符串,返回寻找到的第一个字符串出现的起始位置。

几个注意点:

(1)如果needle是空字符串时,返回0。

(2)取数组中元素时,要保证索引不越界!

(3)不需要遍历haystack中所有的字符,如果haystack遍历到的字符之后的字符组成的长度小于了needle的长度,显然已经不可能了。

时间复杂度与haystack字符子串中与needle的首字符、第二个字符、第三个字符……,即前部分字符相同的数量有关,最差情况下是O(n * m)级别的,其中n为haystack字符串的长度,m为needle字符串的长度,最好情况是O(n)级别的。空间复杂度是O(1)级别的。

JAVA代码:

public class Solution {
	
	public int strStr(String haystack, String needle) {
		int n1 = haystack.length();
		int n2 = needle.length();
        if(n2 == 0) {
        	return 0;
        }
        for (int i = 0; i < n1 - n2 + 1; i++) {
			if(haystack.charAt(i) == needle.charAt(0)) {
				boolean flag = true;
				for(int j = 1; j < n2; j++) {
					if(haystack.charAt(i + j) != needle.charAt(j)) {
						flag = false;
						break;
					}
				}
				if(flag) {
					return i;
				}
			}
		}
        return -1;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82413774