28. Implement strStr()

实现strStr()函数。

返回字符串needle在字符串haystack中第一次出现的下标,如果找不到,返回-1

1. 借助于java中内置的相关函数

  public int strStr(String haystack, String needle) 
    {
        return haystack.indexOf(needle);
    }

2. 常规思路

遍历串haystack中的每一个字符,如果与串needle中的第一个字符相同,就记录下当前haystack串的下标k,

并同时更新haystack串和needle串的下标,如果成功遍历到串needle的尾部,则k即为子串needle的起始

下标,否则,让串haystack从下标k+1开始,继续寻找子串needle,直到到达串haystack的结尾,如果,

找不到就返回-1。

public int strStr(String haystack, String needle)
	{
		int pos = -1;
		int len1 = haystack.length();
		int len2 = needle.length();
		int i = 0;
		int j  = 0;
		int k = 0;
		// 如果needle串比haystack串要长
		if (len2 > len1)
		{
			return pos;
		}
		
		// 串needle为空时,返回0
		if (len2 == 0)
		{
			return 0;
		}
		
		for (i=0; i<len1; i++)
		{
			k = i;
			for (j=0; j<len2 && i<len1; j++)
			{
				if (haystack.charAt(i) == needle.charAt(j))
				{
					i++;
				}
				else
				{
					break;
				}
			}
			// 说明在haystack串中,找到了needle串,返回起始位置即可
			if (j == len2)
			{
				return k;
			}
			i = k;
		}
		return pos;
	}

3. 

// 该代码根据java中indexOf源码改编而成
	public int strStr03(String source, String target)
	{
		int sourceCount = source.length();
		int targetCount = target.length();
		
		// 如果target字符串长度为0,则返回搜索的起始下标
		if (targetCount == 0)
		{
			return 0;
		}
		
		char first = target.charAt(0);
		int max = sourceCount - targetCount; //  两个字符串相差的长度
		
		for (int i=0; i<=max; i++)
		{
			/*Look for first character.*/
			if (source.charAt(i) != first)
			{
				while (++i <= max && source.charAt(i) != first);
			}
			
			/*Found first character, now look at the rest of v2*/
			if (i <= max)
			{
				int j=i+1;
				int end = j + targetCount - 1; // 继续在source中查找的最大长度
				for (int k=1; j<end && source.charAt(j) == target.charAt(k); j++, k++);
				if (j == end)
				{
					/*Found whole string.*/
					return i;
				}
			}
		}
		return -1;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值