【leetcode】28.(Easy)Implement strStr()

题目链接


解题思路:
这道题的意思就是找到字符串中一个子串的起始位置,没有这个子串的话返回-1。
我的做法就是简单的蛮力法,首先找到第一个匹配的字符,然后再进一步进行判决


提交代码:

class Solution {
	public int strStr(String haystack, String needle) {
		if(haystack==null||needle==null)	return -1;
		if (needle.equals(""))	return 0;

		int pos = -1, startpos = 0, p1,p2 = 0;

		while (startpos <= (haystack.length() - needle.length())) {
			// 找到第一个匹配的字符
			if (haystack.charAt(startpos) == needle.charAt(0)) {
				pos = startpos;
				p1=startpos;
				p2=0;
				while (p1 < haystack.length() && p2 < needle.length()
						&& haystack.charAt(p1) == needle.charAt(p2)) {
					p1++;
					p2++;
				}
				if (p2 == needle.length())
					return pos;
			}
			startpos++;
		}
		return -1;
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83903505