ARTS leetcode10 Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

给两个字符串,haystack和needle,找出haystack中第一次出现needle的索引位置,如果haystack中不存在needle,那么就返回-1.

思路:直接可以调用Sting类的indexOf(String str);这个方法,因为具有重载方法,所以一定要选对重载的方法。该方法就是返回在字符串中第一次出现子字符串的位置索引。

class Solution {
    public int strStr(String haystack, String needle) {
        return  haystack.indexOf(needle);
    }
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 37.4 MB, less than 83.90% of Java online submissions for Implement strStr().

别人的实现:

class Solution {
    public int strStr(String haystack, String needle) {
        for (int i = 0; ; i++) {
        for (int j = 0; ; j++) {
          if (j == needle.length()) return i;
          if (i + j == haystack.length()) return -1;
          if (needle.charAt(j) != haystack.charAt(i + j)) break;
        }
      }
    }
}
Runtime: 4 ms, faster than 62.81% of Java online submissions for Implement strStr().
Memory Usage: 38.2 MB, less than 59.53% of Java online submissions for Implement strStr().

别人的手动实现:
1.判断是否为空,为空返回-1
2.不为空情况下开始循环,循环次数为haystack的长度-1,
3.用一个变量来记录第一次出现的匹配字符串的位置
4.该值要小于子字符串长度并且从匹配到的第一个字符的位置开始,两个字符串开始同步匹配,直到匹配结束,如果有不匹配的值,则返回-1.

class Solution {
    public int strStr(String haystack, String needle) {
         if (haystack == null || needle == null)
	        return -1;
	    int l1 = haystack.length();
	    int l2 = needle.length();
	    for (int i = 0; i < l1-l2+1; i++) {
	        int count = 0;
	        while (count < l2 && haystack.charAt(i+count) == needle.charAt(count))
	            count++;
	        if (count == l2)
	            return i;
	    }
	    return -1;
    }
}
Runtime: 1 ms, faster than 99.21% of Java online submissions for Implement strStr().
Memory Usage: 38.6 MB, less than 23.33% of Java online submissions for Implement strStr().
Next challenges:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值