Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【leetcode】Q28实现strStr() #3

Open
0xbitboy opened this issue Jan 30, 2019 · 1 comment
Open

【leetcode】Q28实现strStr() #3

0xbitboy opened this issue Jan 30, 2019 · 1 comment

Comments

@0xbitboy
Copy link
Owner

暴力解法
1.按位匹配,每次发现首字母匹配则记录当前的位置,继续向后匹配。
2.如果匹配过程中发现不匹配了,则回到首字母匹配的位置+1 继续匹配。

@0xbitboy
Copy link
Owner Author

class Solution {
	public int strStr(String haystack, String needle) {

		if("".equals(needle)){
			return 0;
		}

		if(needle.length()>haystack.length()){
			return -1;
		}
		char[] haystackChars = haystack.toCharArray();
		char[] needleChars = needle.toCharArray();
		int index = -1;
		int p = 0;
		for(int i=0;i<haystackChars.length;++i){

			if(p < needleChars.length && haystackChars[i] == needleChars[p]){
				p++;
				if(index == -1){
					index = i;
				}
				if(p==needleChars.length){
					return index;
				}
			}else{
				p=0;
				if(index != -1){
					i = index;
				}
				index = -1;
			}

		}

		return -1;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().strStr("mississippi","pi"));
	}
}

0xbitboy added a commit that referenced this issue Jan 30, 2019
1.按位匹配,每次发现首字母匹配则记录当前的位置,继续向后匹配。
2.如果匹配过程中发现不匹配了,则回到首字母匹配的位置+1 继续匹配。

#3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant